【问题标题】:Return HTML from ASP.NET Web API从 ASP.NET Web API 返回 HTML
【发布时间】:2015-01-05 11:40:21
【问题描述】:

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

我尝试了下面的代码,但由于 Response.Write 未定义而出现编译错误:

public class MyController : ApiController
{
    [HttpPost]
    public HttpResponseMessage Post()
    {
        Response.Write("<p>Test</p>");
        return Request.CreateResponse(HttpStatusCode.OK);
    }
 }

【问题讨论】:

  • 如果要返回 HTML,为什么要使用 WebAPI?我的意思是这就是 ASP.NET MVC 和 ASP.NET WebForms 的用途。
  • 谢谢你,太好了。我将控制器更改为常规控制器。
  • @Stilgar 一个原因可能是他不使用 MVC 堆栈,也不使用任何渲染引擎,但仍想为某些 Html 提供服务器外观。一个用例可能是您有一个 Web Api,它提供一些带有客户端模板引擎的 Html,该引擎将在稍后阶段呈现所有内容。
  • @Stilgar 我遇到的另一个用例是当用户单击您通过电子邮件提供的链接时,返回一个 html 页面以提供帐户创建确认的反馈

标签: c# html asp.net-mvc asp.net-mvc-4 asp.net-web-api


【解决方案1】:

ASP.NET 核心。方法 1

如果您的 Controller 扩展了 ControllerBaseController 您可以使用 Content(...) 方法:

[HttpGet]
public ContentResult Index() 
{
    return base.Content("<div>Hello</div>", "text/html");
}

ASP.NET 核心。方法2

如果您选择不从Controller 类扩展,您可以创建新的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 MVC Core HttpResponseMessage 中不支持
  • @Parshuram 我刚刚检查了你的声明。我可以在 ASP.NET Core 中使用 HttpResponseMessage。它位于 System.Net.Http 下。
  • 哦,谢谢,但现在 MediaTypeHeaderValue 不支持
  • 当我使用 ASP.NET MVC 5 执行此操作时,我得到了响应。我没有得到任何 HTML 内容。我收到的只是“StatusCode:200,ReasonPhrase:'OK',版本:1.1,内容:System.Net.Http.StringContent,标题:{ Content-Type:text/html }”
  • @guyfromfargo 你试过[Produces] 方法吗?
【解决方案2】:

从 AspNetCore 2.0 开始,在这种情况下,建议使用 ContentResult 而不是 Produce 属性。见:https://github.com/aspnet/Mvc/issues/6657#issuecomment-322586885

这不依赖于序列化,也不依赖于内容协商。

[HttpGet]
public ContentResult Index() {
    return new ContentResult {
        ContentType = "text/html",
        StatusCode = (int)HttpStatusCode.OK,
        Content = "<html><body>Hello World</body></html>"
    };
}

【讨论】:

  • 我在 2.0 上根本无法获得“生产”的答案,但这可以正常工作。
  • 如果要显示文件中的 html,只需添加 "var content = System.IO.File.ReadAllText("index.html");"
  • 是的,如果您使用的是 ASP.NET Core 2.0,这就是正确的选择!
  • 如果 HTML 文件在本地目录中并且还链接了 css、js 怎么办。那么我们如何提供文件呢?
  • 对于 Razor 页面,您可以调用 PageModel Content() 方法,而不是直接创建 ContentResult。我不确定这是否也适用于控制器。
猜你喜欢
  • 1970-01-01
  • 2018-07-17
  • 2013-06-23
  • 2016-04-23
  • 2013-09-21
  • 2018-03-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多