ASP.Net Web API GET에 여러 매개 변수를 어떻게 전달해야합니까?
.Net MVC4 웹 API를 사용하여 RESTful API를 (희망적으로) 구현하고 있습니다. 시스템에 몇 가지 매개 변수를 전달하고 몇 가지 작업을 수행 한 다음 개체 목록을 결과로 반환해야합니다. 특히 나는 두 날짜를 지나서 그들 사이에있는 레코드를 반환합니다. 또한 후속 호출이 시스템에서 재 처리되지 않도록 반환 된 레코드를 추적하고 있습니다.
몇 가지 접근 방식을 고려했습니다.
매개 변수를 하나의 단일 JSON 문자열로 직렬화하고 API에서 분리합니다. http://forums.asp.net/t/1807316.aspx/1
쿼리 문자열에 매개 변수를 전달하십시오.
여러 쿼리 매개 변수를 편안한 API에 전달하는 가장 좋은 방법은 무엇입니까?경로에서 매개 변수 정의 : api / controller / date1 / date2
본질적으로 매개 변수가있는 객체를 전달할 수있는 POST를 사용합니다.
웹 API (현재)가 ODATA를 지원하기 때문에 ODATA 연구 나는 아직이 일을 많이하지 않았으므로 익숙하지 않습니다.
적절한 REST 사례는 데이터를 가져올 때 GET을 사용해야 함을 나타냅니다. 그러나 GET은 nullipotent이어야하며 (부작용은 발생하지 않음) API 시스템에 레코드를 표시하여 부작용을 일으키는 특정 구현이 위반되는지 궁금합니다.
또한 변수 매개 변수를 지원하는 문제로 이어졌습니다. 입력 매개 변수 목록이 변경되면 선택 3에 대한 경로를 많이 정의해야하는 번거 로움이 있습니다. 그리고 매개 변수가 런타임에 정의되면 어떻게 될까요?
어쨌든 내 특정 구현의 경우 어떤 선택이 가장 좋습니까?
이 기록 표시는 무엇을 의미합니까? 이것이 로깅 목적으로 만 사용되는 경우이 리소스에 대한 모든 쿼리를 기록하기 때문에 GET을 사용하고 모든 캐싱을 비활성화합니다. 레코드 마킹에 다른 목적이있는 경우 POST를 사용하십시오. 사용자는 자신의 조치가 시스템에 영향을 미치며 POST 방법이 경고임을 알아야합니다.
가장 쉬운 방법은 단순히 사용하는 것 AttributeRouting
입니다.
컨트롤러 내에서 분명합니다. 왜 글로벌 WebApiConfig
파일 에서 이것을 원 하십니까?
예:
[Route("api/YOURCONTROLLER/{paramOne}/{paramTwo}")]
public string Get(int paramOne, int paramTwo)
{
return "The [Route] with multiple params worked";
}
{}
이름은 매개 변수와 일치해야합니다.
간단하지만 이제이 GET
인스턴스에서 여러 매개 변수를 처리 하는 별도의 구성 요소가 있습니다.
WebApiConfig
항목에 새 경로를 추가하십시오 .
예를 들어,
public IEnumerable<SampleObject> Get(int pageNumber, int pageSize) { ..
더하다:
config.Routes.MapHttpRoute(
name: "GetPagedData",
routeTemplate: "api/{controller}/{pageNumber}/{pageSize}"
);
그런 다음 HTTP 호출에 매개 변수를 추가하십시오.
GET //<service address>/Api/Data/2/10
매개 변수를 전달 해야하는 RESTfull API를 구현해야했습니다. Mark의 첫 번째 예제 "api / controller? start = date1 & end = date2"에서 설명한 것과 같은 스타일로 쿼리 문자열의 매개 변수를 전달하여이 작업을 수행했습니다.
컨트롤러 에서 C #의 URL 분할 팁을 사용 했습니까?
// uri: /api/courses
public IEnumerable<Course> Get()
{
NameValueCollection nvc = HttpUtility.ParseQueryString(Request.RequestUri.Query);
var system = nvc["System"];
// BL comes here
return _courses;
}
제 경우에는 Ajax를 통해 WebApi를 다음과 같이 호출했습니다.
$.ajax({
url: '/api/DbMetaData',
type: 'GET',
data: { system : 'My System',
searchString: '123' },
dataType: 'json',
success: function (data) {
$.each(data, function (index, v) {
alert(index + ': ' + v.name);
});
},
statusCode: {
404: function () {
alert('Failed');
}
}
});
이게 도움이 되길 바란다...
http://habrahabr.ru/post/164945/ 에서 우수 솔루션을 찾았습니다 .
public class ResourceQuery
{
public string Param1 { get; set; }
public int OptionalParam2 { get; set; }
}
public class SampleResourceController : ApiController
{
public SampleResourceModel Get([FromUri] ResourceQuery query)
{
// action
}
}
사용 GET을 또는 POST는 명확 의해 설명 @LukLed . 매개 변수를 전달할 수있는 방법과 관련하여 두 번째 접근 방식을 제안하는 것이 좋습니다 ( ODATA 에 대해서도 많이 알지 못함 ).
1.Serializing the params into one single JSON string and picking it apart in the API. http://forums.asp.net/t/1807316.aspx/1
This is not user friendly and SEO friendly
2.Pass the params in the query string. What is best way to pass multiple query parameters to a restful api?
This is the usual preferable approach.
3.Defining the params in the route: api/controller/date1/date2
This is definitely not a good approach. This makes feel some one date2
is a sub resource of date1
and that is not the case. Both the date1
and date2
are query parameters and comes in the same level.
In simple case I would suggest an URI like this,
api/controller?start=date1&end=date2
But I personally like the below URI pattern but in this case we have to write some custom code to map the parameters.
api/controller/date1,date2
Use Parameter Binding as describe completely here : http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
[Route("api/controller/{one}/{two}")]
public string Get(int One, int Two)
{
return "both params of the root link({one},{two}) and Get function parameters (one, two) should be same ";
}
Both params of the root link({one},{two}) and Get function parameters (one, two) should be same
I know this is really old, but I wanted the same thing recently and here's what I found...
public HttpResponseMessage Get([FromUri] string var, [FromUri] string test) {
var retStr = new HttpResponseMessage(HttpStatusCode.OK);
if (var.ToLower() == "getnew" && test.ToLower() == "test") {
retStr.Content = new StringContent("Found Test", System.Text.Encoding.UTF8, "text/plain");
} else {
retStr.Content = new StringContent("Couldn't Find that test", System.Text.Encoding.UTF8, "text/plain");
}
return retStr;
}
So now in your address/URI/...
http(s)://myURL/api/myController/?var=getnew&test=test
Result: "Found Test"
http(s)://myURL/api/myController/?var=getnew&test=anything
Result: "Couldn't Find that test"
public HttpResponseMessage Get(int id,string numb)
{
//this will differ according to your entity name
using (MarketEntities entities = new MarketEntities())
{
var ent= entities.Api_For_Test.FirstOrDefault(e => e.ID == id && e.IDNO.ToString()== numb);
if (ent != null)
{
return Request.CreateResponse(HttpStatusCode.OK, ent);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Applicant with ID " + id.ToString() + " not found in the system");
}
}
}
'Programing' 카테고리의 다른 글
하나의 라이너를 파일 앞에 추가 (0) | 2020.07.03 |
---|---|
Apple은 이메일에서 날짜, 시간 및 주소를 어떻게 찾습니까? (0) | 2020.07.03 |
i- 프레임을 통한 YouTube 비디오 내장 z- 인덱스를 무시 하시겠습니까? (0) | 2020.07.03 |
일부 프로젝트가 여러 솔루션에 포함 된 경우 모든 솔루션에 대한 공통 너겟 패키지 폴더 설정 (0) | 2020.07.02 |
json.dumps와 json.load의 차이점은 무엇입니까? (0) | 2020.07.02 |