【问题标题】:Cannot implicitly convert type 'System.Web.Http.Results.NotFoundResult' to 'System.Collections.Generic.IEnumerable<....>'无法将类型“System.Web.Http.Results.NotFoundResult”隐式转换为“System.Collections.Generic.IEnumerable<....>”
【发布时间】:2015-09-24 02:45:00
【问题描述】:

找不到行时如何返回404?但是,以下代码在return NotFound() 行出现错误。

错误 1 ​​无法将类型“System.Web.Http.Results.NotFoundResult”隐式转换为“System.Collections.Generic.IEnumerable”。存在显式转换(您是否缺少演员表?)

    public IEnumerable<Product> GetProductsByReportId(int rid)
    {
        using (var db = new MyContext())
        {
            var query = from b in db.table where b.rid == rid select b;
            if (query == null)
            {
                return NotFound(); // Error!
            }
            return query.ToList();
        }
    }

【问题讨论】:

  • 值得注意的是,查询永远不会为空——它是一个定义。查询的结果也永远不会为空——它将是空的。在解决主要问题时检查是否正确。

标签: c# asp.net asp.net-web-api


【解决方案1】:

您不能将 System.Web.Http.Results.NotFoundResult 设置/转换为 Product

当GetProductsByReportId的结果为null时,你必须修改调用方法返回404(或消息)。

public IEnumerable<Product> GetProductsByReportId(int rid)
    {
        using (var db = new MyContext())
        {
            var query = from b in db.table where b.rid == rid select b;
            if (query == null)
            {
                return null;
            }
            return query.ToList();
        }
    }

int id = 1;
List<Product> products = GetProductsByReportId(id);
if(products == null) {
    var message = string.Format("Product with id = {0} not found", id);
    HttpError err = new HttpError(message);
    return Request.CreateResponse(HttpStatusCode.NotFound, err);
}

【讨论】:

    【解决方案2】:

    错误消息说明了一切。

    当您的方法签名要返回 IEnumerable&lt;Product&gt; 时,您正试图返回对象 System.Web.Http.Results.NotFoundResult

    你可以做的一件事是:

    if (query == null)
         return null;
    

    然后在调用此方法的代码中,处理列表为空的事实。

    正如你在标签中提到的,asp.net Web api,你可以在你的控制器中做这样的事情(假设你的控制器返回HttpResponseMessage):

    [HttpGet]
    public HttpResponseMessage GetProducts(int id)
    {
        var prods = GetProductsByReportId(id);
        if (prods == null)             
           return Request.CreateResponse(HttpStatusCode.NotFound);
        else
            return Request.CreateResponse(HttpStatusCode.OK, prods);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多