Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return raw string with ApiController?

People also ask

Can ApiController return view?

You don't return a View from an API controller. But you can return API data from an MVC controller. The solution would be to correct the errors, not try to hack the API controller.

Is ApiController deprecated?

There is indeed no particular ApiController class anymore since MVC and WebAPI have been merged in ASP.NET Core. However, the Controller class of MVC brings in a bunch of features you probably won't need when developing just a Web API, such as a views and model binding.

What does the ApiController attribute do?

The [ApiController] attribute applies inference rules for the default data sources of action parameters. These rules save you from having to identify binding sources manually by applying attributes to the action parameters.


You could have your Web Api action return an HttpResponseMessage for which you have full control over the Content. In your case you might use a StringContent and specify the correct content type:

public HttpResponseMessage Get()
{
    return new HttpResponseMessage()
    {
        Content = new StringContent(
            "<strong>test</strong>", 
            Encoding.UTF8, 
            "text/html"
        )
    };
}

or

public IHttpActionResult Get()
{
    return base.ResponseMessage(new HttpResponseMessage()
    {
        Content = new StringContent(
            "<strong>test</strong>", 
            Encoding.UTF8, 
            "text/html"
        )
    });
}

Another possible solution. In Web API 2 I used the base.Content() method of APIController:

    public IHttpActionResult Post()
    {
        return base.Content(HttpStatusCode.OK, new {} , new JsonMediaTypeFormatter(), "text/plain");
    }

I needed to do this to get around an IE9 bug where it kept trying to download JSON content. This should also work for XML-type data by using the XmlMediaTypeFormatter media formatter.

Hope that helps someone.


Just return Ok(value) won't work, it will be threated as IEnumerable<char>.

Instead use return Ok(new { Value = value }) or simillar.


If you are using MVC rather than WebAPI you can use the base.Content method:

return base.Content(result, "text/html", Encoding.UTF8);