ASP.NET Core Web API를 사용하는 것이 좋습니다. ASP.NET 4.x Web API보다 다음과 같은 이점이 있습니다.
- ASP.NET Core는 Windows, macOS 및 Linux에서 최신 클라우드 기반 웹앱을 빌드하기 위한 오픈 소스 플랫폼 간 프레임워크입니다.
- ASP.NET Core MVC 컨트롤러 및 웹 API 컨트롤러가 통합됩니다.
- 테스트 가능성을 고려하여 설계되었습니다.
- Windows, macOS 및 Linux에서 개발하고 실행할 수 있습니다.
- 오픈 소스이며 커뮤니티에 중점을 둡니다.
- 최신 클라이언트 쪽 프레임워크 및 워크플로 개발을 통합합니다.
- 클라우드를 갖춘 환경 기반 구성 시스템입니다.
- 종속성 주입이 기본 제공됩니다.
- 간단한 고성능 모듈식 HTTP 요청 파이프라인을 포함합니다.
- Kestrel, IIS, HTTP.sys, Nginx, Apache 및 Docker에서 호스트하는 기능.
- 병렬 버전 관리.
- 최신 웹 개발을 간소화하는 도구를 포함합니다.
이 항목에서는 ASP.NET Web API가 컨트롤러 작업의 반환 값을 HTTP 응답 메시지로 변환하는 방법을 설명합니다.
Web API 컨트롤러 작업은 다음 중 어느 것을 반환할 수 있습니다.
- void
- HttpResponseMessage
- IHttpActionResult
- 다른 유형
이 중 반환되는 값에 따라 Web API는 다른 메커니즘을 사용하여 HTTP 응답을 만듭니다.
| 반환 형식 | Web API에서 응답을 만드는 방법 |
|---|---|
| void | 빈 204 반환(콘텐츠 없음) |
| HttpResponseMessage | HTTP 응답 메시지로 직접 변환합니다. |
| IHttpActionResult | ExecuteAsync를 호출하여 HttpResponseMessage를 만든 다음, 이를 HTTP 응답 메시지로 변환합니다. |
| 기타 형식 | 직렬화된 반환 값을 응답 본문에 씁니다. 200(성공)을 반환합니다. |
이 항목의 나머지 항목에서는 각 옵션에 대해 자세히 설명합니다.
void
반환 형식이면 Web API는 void상태 코드 204(콘텐츠 없음)를 사용하여 빈 HTTP 응답을 반환합니다.
컨트롤러 예제:
public class ValuesController : ApiController
{
public void Post()
{
}
}
HTTP 응답:
HTTP/1.1 204 No Content
Server: Microsoft-IIS/8.0
Date: Mon, 27 Jan 2014 02:13:26 GMT
HttpResponseMessage
작업이 HttpResponseMessage를 반환하는 경우 Web API는 HttpResponseMessage 개체의 속성을 사용하여 응답을 채우기 위해 반환 값을 HTTP 응답 메시지로 직접 변환합니다.
이 옵션을 사용하면 응답 메시지를 많이 제어할 수 있습니다. 예를 들어 다음 컨트롤러 작업은 Cache-Control 헤더를 설정합니다.
public class ValuesController : ApiController
{
public HttpResponseMessage Get()
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");
response.Content = new StringContent("hello", Encoding.Unicode);
response.Headers.CacheControl = new CacheControlHeaderValue()
{
MaxAge = TimeSpan.FromMinutes(20)
};
return response;
}
}
응답:
HTTP/1.1 200 OK
Cache-Control: max-age=1200
Content-Length: 10
Content-Type: text/plain; charset=utf-16
Server: Microsoft-IIS/8.0
Date: Mon, 27 Jan 2014 08:53:35 GMT
hello
도메인 모델을 CreateResponse 메서드에 전달하는 경우 Web API는 미디어 포맷터를 사용하여 직렬화된 모델을 응답 본문에 씁니다.
public HttpResponseMessage Get()
{
// Get a list of products from a database.
IEnumerable<Product> products = GetProductsFromDB();
// Write the list to the response body.
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, products);
return response;
}
Web API는 요청의 Accept 헤더를 사용하여 포맷터를 선택합니다. 자세한 내용은 콘텐츠 협상을 참조하세요.
IHttpActionResult
IHttpActionResult 인터페이스는 Web API 2에서 도입되었습니다. 기본적으로 HttpResponseMessage 팩터리를 정의합니다. 다음은 IHttpActionResult 인터페이스를 사용할 때의 몇 가지 장점입니다.
- 컨트롤러의 단위 테스트를 간소화합니다.
- HTTP 응답을 만들기 위한 공통 논리를 별도의 클래스로 이동합니다.
- 응답을 생성하는 하위 수준 세부 정보를 숨김으로써 컨트롤러 작업의 의도를 보다 명확하게 만듭니다.
IHttpActionResult에는 HttpResponseMessage 인스턴스를 비동기적으로 만드는 단일 메서드인 ExecuteAsync가 포함되어 있습니다.
public interface IHttpActionResult
{
Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken);
}
컨트롤러 작업이 IHttpActionResult를 반환하는 경우 Web API는 ExecuteAsync 메서드를 호출하여 HttpResponseMessage를 만듭니다. 그런 다음 HttpResponseMessage를 HTTP 응답 메시지로 변환합니다.
다음은 일반 텍스트 응답을 만드는 IHttpActionResult의 간단한 구현입니다.
public class TextResult : IHttpActionResult
{
string _value;
HttpRequestMessage _request;
public TextResult(string value, HttpRequestMessage request)
{
_value = value;
_request = request;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = new HttpResponseMessage()
{
Content = new StringContent(_value),
RequestMessage = _request
};
return Task.FromResult(response);
}
}
컨트롤러 작업 예제:
public class ValuesController : ApiController
{
public IHttpActionResult Get()
{
return new TextResult("hello", Request);
}
}
응답:
HTTP/1.1 200 OK
Content-Length: 5
Content-Type: text/plain; charset=utf-8
Server: Microsoft-IIS/8.0
Date: Mon, 27 Jan 2014 08:53:35 GMT
hello
IHttpActionResult 구현을 System.Web.Http.Results 네임스페이스에 정의된 것으로 더 자주 사용합니다. ApiController 클래스는 이러한 기본 제공 작업 결과를 반환하는 도우미 메서드를 정의합니다.
다음 예제에서 요청이 기존 제품 ID와 일치하지 않는 경우 컨트롤러는 ApiController.NotFound를 호출하여 404(찾을 수 없음) 응답을 만듭니다. 그렇지 않으면 컨트롤러는 제품을 포함하는 200(OK) 응답을 만드는 ApiController.OK를 호출합니다.
public IHttpActionResult Get (int id)
{
Product product = _repository.Get (id);
if (product == null)
{
return NotFound(); // Returns a NotFoundResult
}
return Ok(product); // Returns an OkNegotiatedContentResult
}
기타 반환 형식
다른 모든 반환 형식의 경우 Web API는 미디어 포맷터를 사용하여 반환 값을 직렬화합니다. Web API는 직렬화된 값을 응답 본문에 씁니다. 응답 상태 코드는 200(확인)입니다.
public class ProductsController : ApiController
{
public IEnumerable<Product> Get()
{
return GetAllProductsFromDB();
}
}
이 방법의 단점은 404와 같은 오류 코드를 직접 반환할 수 없다는 것입니다. 그러나 오류 코드 발생 시 HttpResponseException을 throw할 수 있습니다. 자세한 내용은 ASP.NET Web API의 예외 처리를 참조하세요.
Web API는 요청의 Accept 헤더를 사용하여 포맷터를 선택합니다. 자세한 내용은 콘텐츠 협상을 참조하세요.
예제 요청
GET http://localhost/api/products HTTP/1.1
User-Agent: Fiddler
Host: localhost:24127
Accept: application/json
예제 응답
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
Date: Mon, 27 Jan 2014 08:53:35 GMT
Content-Length: 56
[{"Id":1,"Name":"Yo-yo","Category":"Toys","Price":6.95}]