Return HTML from ASP.NET Web API

本文关键字:Web API NET ASP HTML from Return | 更新日期: 2023-09-27 18:29:52

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

我尝试了下面的代码,但由于响应而出现编译错误。写入未定义:

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

Return HTML from ASP.NET Web API

ASP.NET核心。方法1

如果控制器扩展ControllerBaseController,则可以使用Content(...)方法:

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

ASP.NET核心。方法2

如果您选择不从Controller类扩展,则可以创建新的ContentResult:

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

旧版ASP.NET MVC Web API

返回媒体类型为text/html:的字符串内容

public HttpResponseMessage Get()
{
    var response = new HttpResponseMessage();
    response.Content = new StringContent("<div>Hello World</div>");
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
    return response;
}

从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>"
    };
}