【问题标题】:return html file from .Net Core api从 .Net Core api 返回 html 文件
【发布时间】:2017-05-06 11:49:35
【问题描述】:

我正在尝试使用 thisthis 获取 html 文件作为输出,但得到了 error 500

我的应用程序的目标是基于api请求,服务器将请求的输出生成为html文件,并将其发送给用户请求。

使用的代码是:

using Microsoft.AspNetCore.Mvc;  // for Controller, [Route], [HttpPost], [FromBody], JsonResult and Json
using System.IO;   // for MemoryStream
using System.Net.Http; // for HttpResponseMessage
using System.Net;  // for HttpStatusCode
using System.Net.Http.Headers;  // for MediaTypeHeaderValue

namespace server{
    [Route("api/[controller]")]
    public class FileController : Controller{
    [HttpGet]
    public HttpResponseMessage Get()
    {
        string r = @" 
            Hello There
        ";
        var stream = new MemoryStream();
        StreamWriter writer = new StreamWriter(stream);
        writer.Write(r);
        writer.Flush();
        stream.Position = 0;

       // processing the stream.
       byte[] Content = convert.StreamToByteArray(stream);
       var result = new HttpResponseMessage(HttpStatusCode.OK);


        result.Content.Headers.ContentDisposition =
            new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
        {
            FileName = "welcome.html"
        };
        result.Content.Headers.ContentType =
            new MediaTypeHeaderValue("application/octet-stream");

        return result;
    }
  }
}

和:

using System.IO;  // for MemoryStream

namespace server{
    class convert{
            public static byte[] StreamToByteArray(Stream inputStream)
            {
                byte[] bytes = new byte[16384];
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    int count;
                    while ((count = inputStream.Read(bytes, 0, bytes.Length)) > 0)
                    {
                        memoryStream.Write(bytes, 0, count);
                    }
                    return memoryStream.ToArray();
                }
            }
    }
}

我需要返回的结果是一个.html 文件,所以我可以使用var a = window.open(returnedFile, "name"); 之类的JavaScript 在新的浏览器窗口中打开它

【问题讨论】:

  • 您想将页面作为附件发送吗?如果没有,那么这个答案应该可以帮助你stackoverflow.com/questions/38105305/…
  • @MarcusH 我明天会测试它,但它看起来会直接显示在浏览器中,我需要用户接收file 所以使用 JavaScript 我可以在另一个窗口中打开它比打开的像var a = window.open(url, "name");
  • 流媒体是必要的吗?
  • @J.Doe 不确定,我刚刚在我的案例附近的另一个解决方案中找到了这个

标签: .net .net-core asp.net-core-webapi


【解决方案1】:

对于 .NET Core 2 API,您可以使用它

return Content(html, "text/html", Encoding.UTF8);

【讨论】:

    【解决方案2】:

    感谢@Marcus-h 的反馈和回答,我通过使用[Produces("text/html")] 解决了这个问题,返回为string,所以完整的代码是:

    namespace server{
        [Route("api/[controller]")]
        public class FileController : Controller{
            [HttpGet]
            [Produces("text/html")]
            public string Get()
            {
                string responseString = @" 
                <title>My report</title>
                <style type='text/css'>
                button{
                    color: green;
                }
                </style>
                <h1> Header </h1>
                <p>Hello There <button>click me</button></p>
                <p style='color:blue;'>I am blue</p>
                ";
                return responseString;
            }
        }
    }
    

    为了让它在浏览器窗口中打开,我使用了:

    var report = window.open('', 'myReport', 'location=no,toolbar=0');
    // or var report = window.open(''); // if I need the user to be able to use the browser actions, like history
    report.document.title = 'My report';  // if title not added in the server code
    fetch('http://localhost:60000/api/File', {
           method: 'get'
          })
          .then(function(response) {
                return response.text();
          }).then(function(text) { 
                report.document.body.innerHTML = text;
          });
    

    【讨论】:

    • 不错的解决方案! Produces 属性对我来说是新的,将检查一下。
    • 它适用于 .Net core 1.0 但不适用于 2.0,您需要手动为“text/html”添加输出格式化程序,请参阅:github.com/aspnet/Mvc/issues/6657
    【解决方案3】:

    要通过 api 返回一个 html 页面,您可以使用 HttpResponseMessage 并将内容类型设置为“text/html”。 问题是 .net 核心默认不支持 HttpResponseMessage 响应。

    第 1 步

    要从 web api 方法启用响应类型,请按照svicks 很好的答案中的步骤操作。

    第 2 步

    将以下方法应用于控制器

    [HttpGet]
    public HttpResponseMessage Get()
    {
        string responseString = @" 
            Hello There
        ";
        var response = new HttpResponseMessage();
        response.Content =  new StringContent(responseString);
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
        return response;
    }
    

    第 3 步

    直接在window.open方法中调用api,默认会在新窗口中打开(_blank)

    window.open('http://localhost:2222/api/file')
    

    【讨论】:

    • 没有出现responseString,而是得到了输出:{"version":{"major":1,"minor":1,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-1},"content":{"headers":[{"key":"Content-Type","value":["text/html"]}]},"statusCode":200,"reasonPhrase":"OK","headers":[],"requestMessage":null,"isSuccessStatusCode":true}
    • @HasanAYousef 我已经更新了我的答案。我很容易得到预期的结果。你是否像我在示例中显示的那样直接在 window.open 方法中传递 url?
    • 我和我们一样,但得到了我告诉你的结果。
    • @HasanAYousef 更新了我的答案
    • 我将"Microsoft.AspNetCore.Mvc.WebApiCompatShim":"1.1.0" 添加到我的project.json,但出现此错误:Package Microsoft.AspNet.WebApi.Client 5.2.2 is not compatible with netcoreapp1.1 (.NETCoreApp,Version=v1.1) 我使用了所有其他version 号码,但仍然出现相同的错误。
    猜你喜欢
    • 2020-08-30
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多