ASP.NET MVC Core WebAPI项目不返回html

时间:2016-11-24 07:05:08

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

这是我的控制器,我正在发送我的HTML

      public class MyModuleController : Controller
        {
            // GET: api/values
            [HttpGet]
            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;
            }
}

作为回应我得到了这个

    {"version":{"major":1,"minor":1,"build":-1,"revision":-1,

"majorRevision":-1,"minorRevision":-1},"content":{"headers":[{"key":"Content-Type","value":["text/plain;

 charset=utf-8"]}]},"statusCode":200,"reasonPhrase":"OK","headers":[],"requestMessage":null,"isSuccessStatusCode":true}

我只想输出我的html。请任何人帮忙,感谢

2 个答案:

答案 0 :(得分:14)

您可以使用继承ContentResultActionResult。请记住将ContentType设置为text/html

public class MyModuleController : Controller
{
    [HttpGet]
    public IActionResult Get()
    {
        var content = "<html><body><h1>Hello World</h1><p>Some text</p></body></html>";

        return new ContentResult()
        {
            Content = content,
            ContentType = "text/html",
        };
    }
}

它将返回正确的Content-Type:

enter image description here

这会导致浏览器将其解析为HTML:

enter image description here

答案 1 :(得分:3)

感谢@genichm和@ smoksnes,这是我的工作解决方案

    public class MyModuleController : Controller
        {
            // GET: api/values
            [HttpGet]
            public ContentResult Get()
            {
                //return View("~/Views/Index.cshtml");

                return Content("<html><body>Hello World</body></html>","text/html");
            }
  }