How to return HTML from ASP.NET MVC Web API controller?
I tried the code below but got compile error since Response.Write is not defined:
public class MyController : ApiController
{
[HttpPost]
public HttpResponseMessage Post()
{
Response.Write("<p>Test</p>");
return Request.CreateResponse(HttpStatusCode.OK);
}
}
This question is related to
c#
html
asp.net-mvc
asp.net-mvc-4
asp.net-web-api
Starting with AspNetCore 2.0, it's recommended to use ContentResult
instead of the Produce
attribute in this case. See: 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>"
};
}
Source: Stackoverflow.com