清单页总是返回一个请求提供id的异常

本文关键字:请求 id 异常 一个 单页总 返回 | 更新日期: 2023-09-27 18:26:01

我使用的是带有自主机的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/

总是提示错误:

参数字典包含"MyTest.Controller.MyTransactionModelsController"中方法"System.Threading.Tasks.Task"1[System.Web.Http.IHttpActionResult]GetMyTransactionModels(Int32)"的不可为null类型"System.Int32"的参数"id"的null条目。可选参数必须是引用类型、可为null的类型,或者声明为可选参数。

这是管制员:

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

有人能帮忙吗?

清单页总是返回一个请求提供id的异常

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

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

看到这个SO答案我应该使用RouteParameter还是UrlParameter作为Asp.NET web api路由?