【问题标题】:search by string id in mvc web API controller在 mvc Web API 控制器中按字符串 id 搜索
【发布时间】:2015-03-24 20:34:54
【问题描述】:

使用 Northwind 数据库,我可以通过 Int id 搜索表,这很好,但在客户表上,客户 ID 是一个字符串,如果我尝试搜索输入特定的客户,我的 api 控制器将不会运行我可以返回所有但不是个人的字符串 我如何告诉控制器搜索字符串 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);

    }

【问题讨论】:

  • 这里是编译时返回的错误{“'DefaultInlineConstraintResolver'类型的内联约束解析器无法解析以下内联约束:'string'。”}

标签: api model-view-controller asp.net-web-api


【解决方案1】:

您必须删除“字符串”约束,因为 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-01
    相关资源
    最近更新 更多