从 ASP.NET Web API 返回 HTML [英] Return HTML from ASP.NET Web API
本文介绍了从 ASP.NET Web API 返回 HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从 ASP.NET MVC Web API 控制器返回 HTML?
How to return HTML from ASP.NET MVC Web API controller?
我尝试了下面的代码,但由于未定义 Response.Write 出现编译错误:
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);
}
}
推荐答案
ASP.NET Core.方法一
如果你的控制器扩展了 ControllerBase
或 Controller
你可以使用 Content(...)
方法:
ASP.NET Core. Approach 1
If your Controller extends ControllerBase
or Controller
you can use Content(...)
method:
[HttpGet]
public ContentResult Index()
{
return base.Content("<div>Hello</div>", "text/html");
}
ASP.NET 核心.方法二
如果您选择不从 Controller
类扩展,您可以创建新的 ContentResult
:
ASP.NET Core. Approach 2
If you choose not to extend from Controller
classes, you can create new 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;
}
这篇关于从 ASP.NET Web API 返回 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文