列表页面总是返回一个要求提供 id 的异常

Listing page always returned a exception for asking provide id

我正在使用 ASP.NET MVC + WEB API 2,自托管。

这是我自己的房东Startup.cs:

public class SelfHostStartup
{
    // This code configures Web API. The Startup class is specified as a type
    // parameter in the WebApp.Start method.
    public void Configuration(IAppBuilder appBuilder)
    {
        // Configure Web API for self-host. 
        var config = new HttpConfiguration();
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
        ConfigureAuth(appBuilder);

        // Web API routes
        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = UrlParameter.Optional }
        );

        appBuilder.UseWebApi(config);
    }
}

已经指定 id 是可选的,但是访问 url 时:

http://localhost:9000/api/MyTransactionModels/

总是提示错误:

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Threading.Tasks.Task`1[System.Web.Http.IHttpActionResult] GetMyTransactionModels(Int32)' in 'MyTest.Controllers.MyTransactionModelsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.

这是控制器:

public class MyTransactionModelsController : ApiController
{
    private ApplicationDbContext db = new ApplicationDbContext();

    // GET: api/MyTransactionModels
    [Authorize]
    public IQueryable<MyTransactionModel> GetMyTransactionModels()
    {
        return db.MyTransactionModels;
    }

    // GET: api/MyTransactionModels/5
    [ResponseType(typeof(MyTransactionModel))]
    public async Task<IHttpActionResult> GetMyTransactionModels(int id)
    {
        ...
    }
}

虽然 url 的 detail 页面测试结果正确:

http://localhost:9000/api/MyTransactionModels/1

有人可以帮忙吗?

UrlParameter.Optional 更改为 RouteParameter.Optional。前者用于标准 ASP.NET MVC,而后者用于 ASP.NET Web API。他们的行为不同。

刚刚用新创建的 Web API 项目进行了测试,如果我使用 UrlParameter.Optional,我得到的错误与你完全相同,但当它切换到 RouteParameter.Optional 时却没有。

看到这个 SO 答案 Should I use RouteParameter or UrlParameter for an Asp.NET web-api route?