askolotl
askolotl

Reputation: 1006

Cannot return HTML from a Controller

My code fails to return HTML from a Controller. The browser returns HTTP ERROR 500 - "This page does not work".

The Controller is written in .net core 3.1. Here is the code:

[ApiController]
[Route("")]
public class MyController : ControllerBase
{
    [HttpGet]
    public async Task<ActionResult<ContentResult>> GetInformation()
    {
        string s = @"<!DOCTYPE html><html><head><title>.....";
        return base.Content(s, "text/html");
    }
}

However, returning a plain string works: (using string instead of ContentResult. However, this string is not interpreted as HTML and is written directly to the browser)

[ApiController]
[Route("")]
public class MyController : ControllerBase
{
    [HttpGet]
    public async Task<ActionResult<string>> GetInformation()
    {
        string s = @"something";
        return s;
    }
}

Upvotes: 2

Views: 804

Answers (1)

Kirk Larkin
Kirk Larkin

Reputation: 93093

public async Task<ActionResult<ContentResult>> GetInformation()

Because you declare that the action returns an ActionResult<ContentResult>, I expect that the ASP.NET Core serialisation process attempts to serialise the ContentResult you return as a JSON object. This is neither intended nor something the framework can manage.

Controller action return types in ASP.NET Core web API goes into the details, but a more typical method signature for your scenario would look like this:

public async Task<IActionResult> GetInformation()

You could also specify ContentResult, which implements IActionResult, if you'd prefer to do that:

public async Task<ContentResult> GetInformation()

IActionResult allows an action to return different responses in different situations, using e.g. BadRequest, Content, or Ok.

Upvotes: 4

Related Questions