Cannot implicitly convert type 'System.Web.Http.Results.

本文关键字:System Web Http Results implicitly convert type Cannot | 更新日期: 2023-09-27 18:01:20

当没有找到行时如何返回404 ?但是,下面的代码在return NotFound()行上出现了错误。

错误1无法隐式转换类型"System.Web.Http.Results"。NotFoundResult' to '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();
        }
    }

Cannot implicitly convert type 'System.Web.Http.Results.

不能设置/强制转换System.Web.Http.Results。NotFoundResultProduct

当getproductsbyreporttid的结果为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);
}

错误信息说明了一切。

你试图返回对象System.Web.Http.Results.NotFoundResult时,你的方法签名是返回IEnumerable<Product>

你可以这样做:

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