c# - 从 ASP.NET Web API ASP.NET Core 2 返回 HTML 并获取 http 状态 406

标签 c# asp.net-core

这是对 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>在浏览器中(没有错误)。

我错过了什么?谢谢。

最佳答案

作为KTCO指出here :

Starting with AspNetCore 2.0, it's recommended to use ContentResult instead of the Produce 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/

相关文章:

c# - Task.Run a void 方法和 Task 方法返回 null 有区别吗?

c# - Linq2Sql 测试

Azure Cosmos DB .NET SDK - 每 5 分钟后台请求一次?

c# - 如何在 web api 上发布 SOAP 消息(asp.net core -> web api)

asp.net-core - 上传文件到 ASP.Net 5 Web API 时,IFormFile 的集合为空

c# - 控制 ASP.NET Core 操作响应中的 Guid 格式

c# httplistener 只捕获本地ip请求

c# - 如何将 IplImage opencv 转换为字节数组(bmp 格式)C++?

C# VS2010 在应用程序中判断是否被调试

c# - 配置 Strict Cors .Net Core 3.1