Skip to main content
 首页 » 编程设计

c#之无法将类型 'System.Web.Http.Results.NotFoundResult' 隐式转换为 'System.Collections.Generic.IEnumerable....>'

2024年06月03日48yjmyzz

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

Error 1 Cannot implicitly convert type 'System.Web.Http.Results.NotFoundResult' to 'System.Collections.Generic.IEnumerable< webapi.Models.Product>'. An explicit conversion exists (are you missing a cast?)

    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(); 
        } 
    } 

请您参考如下方法:

您不能将 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); 
}