Return HTML from ASP.NET Web API

前端 未结 2 848
孤街浪徒
孤街浪徒 2020-11-30 19:24

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 clas         


        
2条回答
  •  再見小時候
    2020-11-30 19:30

    ASP.NET Core. Approach 1

    If your Controller extends ControllerBase or Controller you can use Content(...) method:

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

    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 = "
    Hello World
    " }; }

    Legacy ASP.NET MVC Web API

    Return string content with media type text/html:

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

提交回复
热议问题