使用Northwind数据库我可以通过Int id搜索表格,但是在客户表上,客户ID是一个字符串,如果我尝试搜索输入特定客户的客户,我的api控制器将无法运行字符串我可以返回所有但不是个人如何告诉控制器搜索字符串ID,即Joe Bloggs CustId = NVAMD?
[RoutePrefix( “API /卡斯特”)]
[RoutePrefix("api/cust")]
public class CustomersController : ApiController
{
private NORTHWNDEntities db = new NORTHWNDEntities();
[Route("getall")]
// GET: api/Customers
public IQueryable<Customer> GetCustomers()
{
return db.Customers;
}
// GET: api/Customers/5
[ResponseType(typeof(Customer))]
[Route("getcustid/{id:string}")]
public dynamic GetCustomer(string id)
{
Customer customer = db.Customers.Find(id);
if (customer == null)
{
return NotFound();
}
return Ok(customer);
}
[Route("getcustadd/{id:string}")]
public dynamic GetCust(string id)
{
Customer cust = db.Customers.Find(id);
if (cust == null)
return NotFound();
return Ok(cust);
}
答案 0 :(得分:3)
您必须删除“字符串”约束,因为Web API 2不支持它
// GET: api/Customers/5
[ResponseType(typeof(Customer))]
[Route("getcustid/{id}")]
public dynamic GetCustomer(string id)
{
Customer customer = db.Customers.Find(id);
if (customer == null)
{
return NotFound();
}
return Ok(customer);
}
您可以在以下链接上阅读更多信息:http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#constraints