加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-web-api – 从ASP.NET Web API ASP.NET Core 2返回HTML

发布时间:2020-12-15 21:00:05 所属栏目:asp.Net 来源:网络整理
导读:这是 Return HTML from ASP.NET Web API的后续行动. 我按照说明操作,但我在浏览器中收到错误406. 我的代码: [Produces("text/html")] [Route("api/[controller]")] public class AboutController : Controller { [HttpGet] public string Get() { return "h
这是 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>欢迎< / 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属性).

我希望这可以帮助别人.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读