首页 > 解决方案 > 如何在 ASP.NET Web 应用程序中显示 PDF 文件

问题描述

我有一个 web api 和一个 web 应用程序,它们都是用 asp.net 编写的,并且想将一个 PDF 从 api 发送到 web 应用程序以在新的浏览器窗口中显示,api 正在将文件作为流内容发送,但我找不到提示客户端浏览器在新窗口中显示此内容的一种方式,我无法让浏览器直接向 api 发出请求,因为我需要先添加身份验证标头。

有没有人有任何想法?

作为替代方案,如果这是不可能的,我也可以将文件下载到客户端计算机,但我也不知道该怎么做。

api代码:

    public HttpResponseMessage Get()
    {
        var response = new HttpResponseMessage();

        string auth;
        try
        {
            auth = Request.Headers.Authorization.Parameter;
        }catch { return new HttpResponseMessage(HttpStatusCode.Unauthorized); }
        if (auth == "test" || auth == null)
        {
            FileStream stream = File.OpenRead(Path.Combine(Storage.FilesDirectory, "0d23b37f-3ade-4342-beea-c6ba2cbf83cb.file"));
            response.Content = new StreamContent(stream);
            response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
            return response;
        }
        else return new HttpResponseMessage(HttpStatusCode.Forbidden);
    }

获取流的当前客户端代码,但我不知道如何在浏览器中显示它:

        HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, API.DocumentUrl);
        req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", "test");
        var res = await HttpClientSingleton.Client.SendAsync(req);

标签: c#asp.netpdfwebasp.net-web-api

解决方案


推荐阅读