【问题标题】:Web API Controller "Multiple actions found"Web API 控制器“找到多个操作”
【发布时间】:2015-09-05 14:02:55
【问题描述】:

我正在使用以下获取请求来查询以下 Web API 控制器,

/api/records?aasdfsdf - 返回记录中的所有内容

/api/records?search=aasdfsdf - 引发以下错误:

“找到多个匹配请求的操作:\r\nGetRecords

有人能解释一下可能是什么原因吗?

  public IQueryable<Record> GetRecord()
    {
       // return db.Records;
    }


    public IQueryable<Record> GetRecord(String search)
    {
        // return db.Record;
    }

    public IQueryable<Ecg> GetEcgs(String search,DateRange date)
    {
         // return db.Record;
    }

    public class DateRange
    {
        public DateTime start { get; set; }
        public DateTime end { get; set; }
    }

还有什么是正确的查询方式:

public IQueryable GetEcgs(String search,DateRange date)

我尝试了以下方法,但遇到了相同的“多项操作”错误。任何帮助将不胜感激。

/api/records?search=asdfsdf?start=2014-09-05%2014:02:17.757&end=2014-09-05%2014:02:17.757

【问题讨论】:

    标签: asp.net asp.net-web-api2


    【解决方案1】:
    /api/records?aasdfsdf
    

    此请求将路由到 GetRecord() 方法,因为您的查询字符串没有任何键值对,因此唯一可能的路由是 GetRecord()

    /api/records?search=aasdfsdf 
    

    此请求可以同时路由到 GetRecord(String search) 和 GetEcgs(String search,DateRange date),日期为空。这就是你有例外的原因。

    您可以将控制器更改为以下以获得所需的路由:

    public IQueryable<Record> GetRecord()
    {
       // return db.Records;
    }
    
    public object GetRecord(String search, DateTime? start, DateTime? end)
    {
        if( start.HasValue && end.HasValue )
        {
            return this.GetEcgs(search, new DateRange(start,end));
        }
    
        return this.GetRecord(search);
    }
    
    //use private so it's not a possible route or use [NonAction]
    private IQueryable<Record> GetRecord(String search)
    {
        // return db.Record;
    }
    
    private IQueryable<Ecg> GetEcgs(String search, DateRange date)
    {
         // return db.Record;
    }
    

    如果 Ecg 和 Record 都是同一个基类,您可以返回 IQueryable 而不仅仅是对象。在我们的 web api 项目中,我们不使用控制器来返回两种不同的类型,或者我们像这样使用 IHttpActionResult:

    public IHttpActionResult GetRecord()
    {
       // return this.Ok(db.Records);
    }
    
    public IHttpActionResult GetRecord(String search, DateTime? start, DateTime? end)
    {
        if( start.HasValue && end.HasValue )
        {
            return this.GetEcgs(search, new DateRange(start,end));
        }
    
        return this.GetRecord(search);
    }
    
    //use private so it's not a possible route or use [NonAction]
    private IHttpActionResult GetRecord(String search)
    {
        // return this.Ok(db.Record);
    }
    
    private IHttpActionResult GetEcgs(String search, DateRange date)
    {
         // return this.Ok(db.Record);
    }
    

    这感觉比返回“对象”要好得多,但是如果您有将在控制器之后运行的自定义过滤器,那么您将需要返回对象而不是结果,因此您的使用会有所不同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-24
      • 1970-01-01
      • 1970-01-01
      • 2014-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多