11

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

13
  • That is an Mvc controller, not an apicontroller. Change your base class to ApiController first. Commented Nov 24, 2016 at 7:11
  • @Mathew - If you use asp.net core, all of them are derived from Controller class Commented Nov 24, 2016 at 7:12
  • Ok, sorry, I dont have enough exp in core. Commented Nov 24, 2016 at 7:13
  • Do you have to return html from the API? The API generally for returning data and not HTML. Commented Nov 24, 2016 at 7:14
  • 1
    try to do it this way [HttpGet] public ContentResult Get() { return Content("<b>a</b>", "text/html"); } It worked for me once in .NET Core Commented Nov 24, 2016 at 7:41

2 Answers 2

26

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

Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.