api - 在 mvc Web API Controller 中按字符串 id 搜索

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

使用 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/

相关文章:

java - 哪个更好,编写另一种方法还是向现有方法添加更多参数?

c# - 关于 ASP.NET 的表单例份验证和 session 的滑动到期

jquery - ASP.Net Web Api 是否在单独的 Web 应用程序中?

c# - 解析 nlog.config 时出现 NLog 异常 - 找不到目标 : 'EventLog'

python - 为什么 Github API 允许我访问但不列出私有(private)仓库?

javascript - 将 Canvas 发布到 web api

mysql - Ruby on Rails 模型无法识别预加载?

javascript - Sencha Architect 自动创建 ViewModel 和 View Controller

java - Spring 将 JSON 映射到 java POJO

python - 使用created_at过滤器查询Soundcloud API