Подтвердить что ты не робот

Возврат HTML из веб-API ASP.NET

Как вернуть HTML из ASP.NET MVC Web API-контроллера?

Я попробовал код ниже, но получил ошибку компиляции, так как Response.Write не определен:

public class MyController : ApiController
{
    [HttpPost]
    public HttpResponseMessage Post()
    {
        Response.Write("<p>Test</p>");
        return Request.CreateResponse(HttpStatusCode.OK);
    }
 }
4b9b3361

Ответ 1

ASP.NET Core. Подход 1

Если ваш контроллер расширяет ControllerBase или Controller, вы можете использовать метод Content(...):

[HttpGet]
public ContentResult Index() 
{
    return base.Content("<div>Hello</div>", "text/html");
}

ASP.NET Core. Подход 2

Если вы решите не расширять классы Controller, вы можете создать новый ContentResult:

[HttpGet]
public ContentResult Index() 
{
    return new ContentResult 
    {
        ContentType = "text/html",
        Content = "<div>Hello World</div>"
    };
}

Устаревший веб-API ASP.NET MVC

Возврат содержимого строки с типом носителя text/html:

public HttpResponseMessage Get()
{
    var response = new HttpResponseMessage();
    response.Content = new StringContent("<div>Hello World</div>");
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
    return response;
}

Ответ 2

Начиная с AspNetCore 2.0, в этом случае рекомендуется использовать ContentResult вместо атрибута Produce. Смотрите: https://github.com/aspnet/Mvc/issues/6657#issuecomment-322586885

Это не зависит ни от сериализации, ни от согласования контента.

[HttpGet]
public ContentResult Index() {
    return new ContentResult {
        ContentType = "text/html",
        StatusCode = (int)HttpStatusCode.OK,
        Content = "<html><body>Hello World</body></html>"
    };
}