这是对 Return HTML from ASP.NET Web API 的跟进.
我按照说明进行操作,但在浏览器中收到错误 406。 我的代码:
[Produces("text/html")]
[Route("api/[controller]")]
public class AboutController : Controller
{
[HttpGet]
public string Get()
{
return "<html><body>Welcome</body></html>";
}
...
并且,简单地说:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
当我删除 Produces
行我得到纯文本 <html><body>Welcome</body></html>
在浏览器中(没有错误)。
我错过了什么?谢谢。
最佳答案
Starting with AspNetCore 2.0, it's recommended to use
ContentResult
instead of theProduce
attribute
解决方法是:
[HttpGet]
public ContentResult Get()
{
return new ContentResult {
ContentType = "text/html",
StatusCode = (int) HttpStatusCode.OK,
Content = "<html><body>Welcome</body></html>"
};
}
无需更改 AddMvc
(当然也没有 Produce
属性)。
我希望这对某人有帮助。
关于c# - 从 ASP.NET Web API ASP.NET Core 2 返回 HTML 并获取 http 状态 406,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46793783/