web-dev-qa-db-ja.com

ASP.NETMVCコアWebAPIプロジェクトがHTMLを返さない

これが私の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を出力したいだけです。誰か助けてください、ありがとう

ContentResult を使用できます。これは ActionResult を継承します。 ContentTypetext/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

17
smoksnes

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