且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从的ASP.NET Web API返回的HTML

更新时间:2023-02-15 20:14:17

返回HTML字符串

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

 公开的Htt presponseMessage的get()
{
    VAR响应=新的Htt presponseMessage();
    response.Content =新的StringContent(< HTML和GT;<身体GT;的Hello World< /身体GT;< / HTML>中);
    response.Content.Headers.ContentType =新MediaTypeHeaderValue(text / html的);
    返回响应;
}

从网页API返回的Razor视图

您需要使用您的NuGet控制台安装封装RazorEngine

 使用RazorEngine;
使用RazorEngine.Templating;


 字符串razorTemplate =你好!@Model
字符串的html = Engine.Razor.RunCompile(
    razorTemplate,
    uniqueTemplateKey
    modelType:typeof运算(字符串),
    模式:Lorem存有);

现在我们可以用code从previous例如从网页API返回的HTML字符串。

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);
    }
 }

Return HTML string

Return string content with media type text/html:

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

Returning Razor view from Web API

You need to Install-Package RazorEngine using your NuGet console.

using RazorEngine;
using RazorEngine.Templating;


string razorTemplate = "Hello @Model!";
string html = Engine.Razor.RunCompile(
    razorTemplate, 
    "uniqueTemplateKey", 
    modelType: typeof(string), 
    model: "Lorem Ipsum");

Now we can use code from the previous example to return HTML string from Web API.