c# - 如何从服务器加载 pdf 作为 aspx 页面(或安全加载 pdf 文件)?

标签 c# .net asp.net pdf

我有一个包含 pdf 的文件夹,但我不希望它们公开(就像只输入 www.domain.com/pdfs/doc.pdf)。

我需要他们采取某种安全措施(例如 www.domain.com/loadpdf.asmx?key=23452ADFASD12345 或使用 POST)

我该怎么做?我知道如何创建 pdf,但不知道如何从服务器加载 PDF。

谢谢。

最佳答案

将 PDF 读入字节数组并使用它。正如 awright18 所说,在处理程序 (.ashx) 中执行此操作。像这样的事情:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class MapHandler : IHttpHandler, IReadOnlySessionState
{

    public void ProcessRequest(HttpContext context) {
        CreateImage(context);
    }

    private void CreateImage(HttpContext context) {

        string documentFullname = // Get full name of the PDF you want to display...

        if (File.Exists(documentFullname)) {

            byte[] buffer;

            using (FileStream fileStream = new FileStream(documentFullname, FileMode.Open, FileAccess.Read, FileShare.Read))
            using (BinaryReader reader = new BinaryReader(fileStream)) {
                buffer = reader.ReadBytes((int)reader.BaseStream.Length);
            }

            context.Response.ContentType = "application/pdf";
            context.Response.AddHeader("Content-Length", buffer.Length.ToString());
            context.Response.BinaryWrite(buffer);
            context.Response.End();

        } else {
            context.Response.Write("Unable to find the document you requested.");
        }
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

我找到了this thread这里非常有用,但是上面的内容应该对您有用。

关于c# - 如何从服务器加载 pdf 作为 aspx 页面(或安全加载 pdf 文件)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2300584/

相关文章:

c# - 我应该有两个不同的模型类来读取和更新 Web API 中的对象吗?

javascript - 对所有用户使用 Office 365 身份验证

c# - 使用 C# 播放 MIDI 声音的最佳方式

c# - 来自 html 文件的 HtmlHelper

c# - 保护输入 SQL 的数据免受不良行为的影响

c# - 如何从另一个类库项目中的 app.config 获取连接字符串?

c# - 在 C# 中通过 HttpWebRequest 实现 Digest 身份验证

c# - 在鼠标点击 PictureBox 时弹出一个 TextBox 以向图片添加自定义注释

c# - 在 WCF REST 服务中返回非 JSON、非 XML 数据

c# - 如何为当前用户(Sitecore)添加新的访客标签?