【问题标题】:ASP.NET MVC Core WebAPI project not returning htmlASP.NET MVC Core WebAPI 项目不返回 html
【发布时间】:2016-11-24 07:05:08
【问题描述】:

这是我的控制器,我正在发送我的 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。请任何人帮忙,谢谢

【问题讨论】:

  • 那是 Mvc 控制器,不是 apicontroller。首先将您的基类更改为ApiController
  • @Mathew - 如果你使用 asp.net core,它们都是从 Controller 类派生的
  • 好的,对不起,我没有足够的核心经验。
  • 是否必须从 API 返回 html? API 通常用于返回数据而不是 HTML。
  • 尝试这样做 [HttpGet] public ContentResult Get() { return Content("a", "text/html");它曾经在 .NET Core 中为我工作过

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


【解决方案1】:

您可以使用ContentResult,它继承了ActionResult。请记住将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:

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

【讨论】:

    【解决方案2】:

    感谢@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");
                }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-24
      • 1970-01-01
      • 1970-01-01
      • 2017-04-09
      • 1970-01-01
      • 2017-07-13
      • 2019-07-28
      • 1970-01-01
      相关资源
      最近更新 更多