[英]Return HTML from ASP.NET Web API
How to return HTML from ASP.NET MVC Web API controller? 如何从ASP.NET MVC Web API控制器返回HTML?
I tried the code below but got compile error since Response.Write is not defined: 我尝试了以下代码,但由于未定义Response.Write,因此出现了编译错误:
public class MyController : ApiController
{
[HttpPost]
public HttpResponseMessage Post()
{
Response.Write("<p>Test</p>");
return Request.CreateResponse(HttpStatusCode.OK);
}
}
If your Controller extends ControllerBase
or Controller
you can use Content(...)
method: 如果您的Controller扩展了
ControllerBase
或Controller
,则可以使用Content(...)
方法:
[HttpGet]
public ContentResult Index()
{
return base.Content("<div>Hello</div>", "text/html");
}
If you choose not to extend from Controller
classes, you can create new ContentResult
: 如果选择不从
Controller
类扩展,则可以创建新的ContentResult
:
[HttpGet]
public ContentResult Index()
{
return new ContentResult
{
ContentType = "text/html",
Content = "<div>Hello World</div>"
};
}
Return string content with media type text/html
: 返回媒体类型为
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;
}
Starting with AspNetCore 2.0, it's recommended to use ContentResult
instead of the Produce
attribute in this case. 从AspNetCore 2.0开始,在这种情况下,建议使用
ContentResult
而不是Produce
属性。 See: https://github.com/aspnet/Mvc/issues/6657#issuecomment-322586885 参见: https : //github.com/aspnet/Mvc/issues/6657#issuecomment-322586885
This doesn't rely on serialization nor on content negotiation.
这不依赖于序列化也不依赖于内容协商。
[HttpGet]
public ContentResult Index() {
return new ContentResult {
ContentType = "text/html",
StatusCode = (int)HttpStatusCode.OK,
Content = "<html><body>Hello World</body></html>"
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.