【问题标题】:Returning generated HTML from .NET Core controller从 .NET Core 控制器返回生成的 HTML
【发布时间】:2021-12-09 05:30:12
【问题描述】:

我有一个 .NET Core 2 应用程序,它需要能够从控制器返回生成的 HTML。我已经能够让它以纯文本形式返回 HTML,但不能说服浏览器它是 HTML 并呈现它;一旦提供了 HTML 内容类型,内容类型协商似乎会破坏它,它只会呈现 406 Not Acceptable。

我尝试过的(简化的)选项 -

    [HttpGet]
    [Produces("text/html")]
    public string Display()
    {
        return "<html><head><title>Testing</title><head><body>Hello, world!</body></html>";
    }

    [HttpGet]
    [Produces("text/html")]
    public HttpResponseMessage Display()
    {
        try
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("<html><head><title>Testing</title><head><body>Hello, world!</body></html>")
            };
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");

            return response;
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
            return new HttpResponseMessage(HttpStatusCode.InternalServerError);
        }
    }

    [HttpGet]
    [Produces("text/html")]
    public IActionResult Display()
    {
        var pageHtml = "<html><head><title>Testing</title><head><body>Hello, world!</body></html>";
        var result = StatusCode(200, pageHtml);
        result.ContentTypes.Add(new MediaTypeHeaderValue("text/html"));

        return StatusCode(200, pageHtml);
    }

Startup.ConfigureServices 方法已经尝试了所有我能想到的 RespectBrowserAcceptHeaderReturnHttpNotAcceptable 属性的组合,但它们似乎没有任何区别。

谁能看到我在说服服务器只返回生成的 HTML 时遗漏了什么?

【问题讨论】:

标签: c# .net-core


【解决方案1】:

您如何/为什么要自己生成 html?我认为更简单的解决方案可能是制作一个 ASP.NET Core 2 MVC 应用程序。这将允许您使用 ViewModel。我会研究一下。

无论如何,尝试返回Content...这将返回 200 的 Http 状态代码,并允许您返回一个字符串,其中包含有关内容格式的其他详细信息。

[HttpGet]
[Produces("text/html")]
public IActionResult Display()
{
     return Content("<html><h1>hello world!</h1></html>", "text/html", Encoding.UTF8);
}

【讨论】:

  • 这是一个不寻常的要求,我同意,但在这种情况下绝对比更标准的方法(已经尝试过)要好。谢谢 - 有效:-)
猜你喜欢
  • 2018-04-09
  • 2020-02-18
  • 2016-01-21
  • 2017-05-06
  • 2023-03-25
  • 1970-01-01
  • 2018-04-28
  • 1970-01-01
  • 2019-05-07
相关资源
最近更新 更多