从ASP.NET Web API返回HTML

And*_*rus 108 html c# asp.net-mvc asp.net-mvc-4 asp.net-web-api

如何从ASP.NET MVC Web API控制器返回HTML?

我尝试了下面的代码,但由于没有定义Response.Write,因此出现了编译错误:

public class MyController : ApiController
{
    [HttpPost]
    public HttpResponseMessage Post()
    {
        Response.Write("<p>Test</p>");
        return Request.CreateResponse(HttpStatusCode.OK);
    }
 }
Run Code Online (Sandbox Code Playgroud)

And*_*rei 233

返回HTML字符串

返回媒体类型的字符串内容ControllerBase:

[HttpGet]
public ContentResult Index() 
{
    return base.Content("<div>Hello</div>", "text/html");
}
Run Code Online (Sandbox Code Playgroud)

ASP.NET核心

最简单的方法是使用"Produces"过滤器:

[HttpGet]
public ContentResult Index() 
{
    return new ContentResult 
    {
        ContentType = "text/html",
        Content = "<div>Hello World</div>"
    };
}
Run Code Online (Sandbox Code Playgroud)

有关Controller属性的更多信息,请点击此处.

  • 当我使用ASP.NET MVC 5执行此操作时,得到响应。我没有得到任何HTML内容。我收到的只是“ StatusCode:200,ReasonPhrase:'OK',版本:1.1,内容:System.Net.Http.StringContent,标题:{Content-Type:text / html}” (2认同)

KTC*_*TCO 52

从AspNetCore 2.0开始,建议在这种情况下使用ContentResult而不是Produce属性.请参阅:https://github.com/aspnet/Mvc/issues/6657#issuecomment-322586885

这不依赖于序列化也不依赖于内容协商.

[HttpGet]
public ContentResult Index() {
    return new ContentResult {
        ContentType = "text/html",
        StatusCode = (int)HttpStatusCode.OK,
        Content = "<html><body>Hello World</body></html>"
    };
}
Run Code Online (Sandbox Code Playgroud)

  • 我无法在2.0上得到"生产"的答案,但是工作正常. (4认同)
  • 是的,如果你使用的是ASP.NET Core 2.0,那么这就是你要走的路! (4认同)