IT

ASP.NET Web API에서 HTML 반환

lottoking 2020. 8. 9. 09:18
반응형

ASP.NET Web API에서 HTML 반환


ASP.NET MVC Web API 컨트롤러에서 HTML을 반환하는 방법은 무엇입니까?

아래 코드를 시도했지만 Response.Write가 정의되지 않았 음을 오류가 발생했습니다.

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

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

레거시 ASP.NET MVC 웹 API

미디어 유형이있는 암호화 콘텐츠 반환 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;
}

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

참고 URL : https://stackoverflow.com/questions/26822277/return-html-from-asp-net-web-api

반응형