【发布时间】: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 方法已经尝试了所有我能想到的 RespectBrowserAcceptHeader 和 ReturnHttpNotAcceptable 属性的组合,但它们似乎没有任何区别。
谁能看到我在说服服务器只返回生成的 HTML 时遗漏了什么?
【问题讨论】:
-
您不能使用解释标记。这是一个特殊的字符。请参阅:en.wikipedia.org/wiki/…