ID, 바코드, 검색어로 제품을 검색하거나 날짜 이후 모든 제품을 검색 할 수있는 ASP.NET MVC4 json Web API를 만드는 방법은 무엇입니까?
아래에서 ASP.NET MVC4 컨트롤러를 사용해 보았습니다.
부름
http://localhost:52216/admin/api/Products/GetSince?since=2014-03-16%2021:47:29&_=1395007124964
오류를 반환
Multiple actions were found that match the request:
System.Net.Http.HttpResponseMessage GetSince(System.String) on type MyApp.Controllers.ProductsController\r\n
System.Net.Http.HttpResponseMessage GetId(System.String) on type MyApp.Controllers.ProductsController"
이 문제를 해결하는 방법? 이 코드는보기 흉해 보이며 유사한 메서드가 많이 포함되어 있습니다. 그러한 API를 만드는 가장 좋은 방법은 무엇입니까? 이 코드를 개선하는 방법은 무엇입니까? Http GET 메서드를 사용해야하지만 메서드 이름과 서명을 변경할 수 있습니다.
ASP.NET/Mono MVC4, jquery, jquery UI가 사용됩니다. Windows 2003 서버도 지원해야하므로 .NET 4.5 또는 MVC5를 사용할 수 없습니다.
public class ProductsController : ApiController
{
[HttpGet]
public HttpResponseMessage GetSince([FromUri]string since))
{
var toodelist = GetProducts(since, null, null, null);
return Request.CreateResponse(HttpStatusCode.OK,
new { products = toodelist.ToArray() });
}
[HttpGet]
public HttpResponseMessage GetId([FromUri]string id)
{
var toodelist = GetProducts(null, null, id, null);
return Request.CreateResponse(HttpStatusCode.OK,
new { products = toodelist.ToArray() });
}
[HttpGet]
public HttpResponseMessage GetBarcode([FromUri]string barcode)
{
var toodelist = GetProducts(null, barcode, null, null);
return Request.CreateResponse(HttpStatusCode.OK,
new { products = toodelist.ToArray() });
}
[HttpGet]
public HttpResponseMessage GetTerm([FromUri]string term)
{
var toodelist = GetProducts(null, null, null, term);
return Request.CreateResponse(HttpStatusCode.OK,
new { products = toodelist.ToArray() });
}
static List<Product> GetProducts(string since, string barcode, string id, string term)
{
... retrieves list of product from database using specified search criteria
if not null
}
}
이와 같은 검색 기준 DTO를 사용하는 것은 어떻습니까?
public class SearchCriteria
{
public int? Id { get; set; }
public DateTime? Since { get; set; }
// Other properties
}
동작 방법은 다음과 같습니다.
public class ProductsController : ApiController
{
public HttpResponseMessage GetProducts([FromUri]SearchCriteria crit))
{
// Validate and clean crit object
var list = GetProducts(crit);
// return list
}
}
GetProducts
SearchCriteria
개체에 설정된 속성을 기반으로 제품 목록을 반환 할 수 있습니다 . 쿼리 문자열 필드가없는 경우 해당 속성은 null입니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다