FromBody와 FromUri를 지정해야하는 이유는 무엇입니까?
ASP.NET 웹 API에 FromBody
및 FromUri
속성이 필요한 이유는 무엇 입니까?
속성을 사용하는 것과 사용하지 않는 것의 차이점은 무엇입니까?
ASP.NET 웹 API는 컨트롤러에서 메소드를 호출 할 때 매개 변수 바인딩 이라는 프로세스 매개 변수의 값을 설정해야합니다 .
기본적으로 Web API는 다음 규칙을 사용하여 매개 변수를 바인드합니다.
매개 변수가 "단순"유형 인 경우 Web API는 URI 에서 값을 가져 오려고 시도합니다 . 간단한 형식에는 .NET 기본 형식 (int, bool, double 등)과 TimeSpan, DateTime, Guid, decimal 및 string과 문자열에서 변환 할 수있는 형식 변환기가있는 형식이 포함됩니다.
복잡한 유형의 경우 Web API는 미디어 유형 포맷터를 사용하여 메시지 본문에서 값을 읽으려고합니다 .
따라서 위의 기본 동작을 무시하고 Web API가 URI에서 복합 유형을 읽도록하려면 [FromUri]
속성을 매개 변수에 추가하십시오 . Web API가 요청 본문에서 단순 유형을 읽도록하려면 [FromBody]
속성을 매개 변수에 추가하십시오 .
따라서 귀하의 질문에 대답하기 위해 Web API에서 [FromBody]
및 [FromUri]
속성 의 필요성은 필요한 경우 위에서 설명한 기본 동작을 재정의하는 것입니다. 여기에 설명 된대로 컨트롤러 메소드에는 두 가지 속성을 사용할 수 있지만 다른 매개 변수에만 사용할 수 있습니다 .
이 훨씬 더 정보 는 "매개 변수 바인딩 웹 API를"구글 경우 웹은.
기본 동작은 다음과 같습니다.
매개 변수가있는 경우 기본 유형 (
int
,bool
,double
, ...), 웹 API의 시도는의 값 얻을 URI 는 HTTP 요청을.들어 복잡한 유형 (예를 들어 자신의 개체, :
Person
), 웹 API의 시도는의 값 읽어 몸 HTTP 요청의를.
따라서 다음이있는 경우
- URI의 기본 유형 또는
- 신체의 복잡한 유형
... 당신은 어떤 속성 (도 추가 할 필요가 없습니다 [FromBody]
아니다 [FromUri]
).
당신이있는 경우에, 원시 형 의 몸을 , 당신은 추가 할 필요가 [FromBody]
당신의 WebAPI 컨트롤러 방법에 원시 형식 매개 변수 앞에. (기본적으로 WebAPI는 HTTP 요청의 URI에서 기본 유형을 찾고 있기 때문입니다.)
또는 URI에 복합 유형 이 있으면을 추가해야합니다 . (기본적으로 WebAPI는 기본적으로 HTTP 요청 본문에서 복잡한 유형을 찾습니다.)[FromUri]
기본 유형 :
public class UsersController : ApiController
{
// api/users
public HttpResponseMessage Post([FromBody]int id)
{
}
// api/users/id
public HttpResponseMessage Post(int id)
{
}
}
복잡한 유형 :
public class UsersController : ApiController
{
// api/users
public HttpResponseMessage Post(User user)
{
}
// api/users/user
public HttpResponseMessage Post([FromUri]User user)
{
}
}
HTTP 요청에 하나의 매개 변수 만 보내면 작동합니다 . 여러 개를 보낼 때 다음과 같은 모든 매개 변수가 포함된 사용자 지정 모델 을 만들어야합니다.
public class MyModel
{
public string MyProperty { get; set; }
public string MyProperty2 { get; set; }
}
[Route("search")]
[HttpPost]
public async Task<dynamic> Search([FromBody] MyModel model)
{
// model.MyProperty;
// model.MyProperty2;
}
From Microsoft's documentation for parameter binding in ASP.NET Web API:
When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object). At most one parameter is allowed to read from the message body.
This should work:
public HttpResponseMessage Post([FromBody] string name) { ... }
This will not work:
// Caution: This won't work! public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }
The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once.
When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object).
At most one parameter is allowed to read from the message body. So this will not work:
// Caution: Will not work!
public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }
The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once
Please go through the website for more details : http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
Just addition to above answers ..
[FromUri] can also be used to bind complex types from uri parameters instead of passing parameters from querystring
For Ex..
public class GeoPoint
{
public double Latitude { get; set; }
public double Longitude { get; set; }
}
[RoutePrefix("api/Values")]
public ValuesController : ApiController
{
[Route("{Latitude}/{Longitude}")]
public HttpResponseMessage Get([FromUri] GeoPoint location) { ... }
}
Can be called like:
http://localhost/api/values/47.678558/-122.130989
참고URL : https://stackoverflow.com/questions/24625303/why-do-we-have-to-specify-frombody-and-fromuri
'Programing' 카테고리의 다른 글
es6 Arrow Functions에서 언제 'return'을 사용해야합니까? (0) | 2020.06.25 |
---|---|
vs (0) | 2020.06.25 |
IEnumerable (0) | 2020.06.25 |
SQLAlchemy : 실제 쿼리 인쇄 (0) | 2020.06.25 |
같은 클래스에서 두 개의 메소드를 동기화하면 동시에 실행할 수 있습니까? (0) | 2020.06.25 |