如何创建ASP.NET MVC4 json Web API,允许按ID,条形码,搜索词搜索产品或检索自日期以来的所有产品?
我试图在下面使用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 Server,因此不能使用.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] 删除。
我来说两句