从的ASP.NET Web API返回的HTML [英] Return HTML from ASP.NET Web API

查看:412
本文介绍了从的ASP.NET Web API返回的HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我试过低于code,但得到编译错误,因为的Response.Write没有定义的:

 公共类myController的:ApiController
{
    [HttpPost]
    公众的Htt presponseMessage邮报()
    {
        回复于(&所述p为H.;试验&下; / P>中);
        返回Request.CreateResponse(的HTTPStatus code.OK);
    }
 }


解决方案

返回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.

这篇关于从的ASP.NET Web API返回的HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆