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

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

找不到行如何返回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);
}

关于c# - 无法将类型 'System.Web.Http.Results.NotFoundResult' 隐式转换为 'System.Collections.Generic.IEnumerable<....>',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31254567/

相关文章:

c# - C# 何时可以推断参数的类型?

C#密码加密

c#-4.0 - 编写要在 Web API MessageHandler 中使用的解压缩机制

c# - MVC Web API 5 升级以支持 CORS

c# - 请在特定于平台的项目中调用 CachedImageRenderer.Init 方法以使用 FFImageLoading?

c# - 内置异常处理的任务?

asp.net - SiteMapResolve 不触发

c# - 无法识别 Web API 路由

c# - 将 C 结构编码到 C#

c# - 在 ASP 网页中分页?