Parshuram Kalvikatte
Parshuram Kalvikatte

Reputation: 1646

ASP.NET MVC Core WebAPI project not returning html

Here is my controller i am sending my 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;
            }
}

In response i am getting this

    {"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}

I just want my html in output.Please can anyone help,Thanku

Upvotes: 11

Views: 9985

Answers (2)

Parshuram Kalvikatte
Parshuram Kalvikatte

Reputation: 1646

Thanku to @genichm and @smoksnes,this is my working solution

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

Upvotes: 5

smoksnes
smoksnes

Reputation: 10851

You can use ContentResult, which inherits ActionResult. Just remember to set ContentType to 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",
        };
    }
}

It will return a correct Content-Type:

enter image description here

Which will cause the browser to parse it as HTML:

enter image description here

Upvotes: 26

Related Questions