我有一个HTMLCore2应用程序,需要能够返回从控制器生成的.Net。我已经能够让它以纯文本的形式返回HTML,但不能说服浏览器它是HTML并呈现它;一旦提供了HTML内容类型,内容类型协商似乎就破坏了它,它只是呈现了一个406不可接受的结果。
(简化)我尝试过的选项-
[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时遗漏了什么吗?
发布于 2019-05-14 10:12:23
你如何/为什么自己生成html?我认为一个更简单的解决方案可能是制作一个ASP.NET Core2MVC应用程序。这将允许您使用ViewModels。我会去看看这个。
无论如何,尝试返回Content
...这将返回一个Http状态码200,并允许您返回一个字符串,其中包含有关如何格式化内容的其他详细信息。
[HttpGet]
[Produces("text/html")]
public IActionResult Display()
{
return Content("<html><h1>hello world!</h1></html>", "text/html", Encoding.UTF8);
}
https://stackoverflow.com/questions/56120838
复制相似问题