使用 Northwind 数据库,我可以通过 Int id 搜索表,这很好,但在客户表上,客户 ID 是一个字符串,如果我尝试搜索输入特定的客户,我的 api Controller 将不会运行我可以返回所有字符串,但不能返回单个字符串,如何告诉 Controller 搜索字符串 id,即 Joe Bloggs CustId=NVAMD ?
[RoutePrefix("api/cust")]
[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);
}
最佳答案
您必须删除“字符串”约束,因为 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
关于api - 在 mvc Web API Controller 中按字符串 id 搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29232417/