Shawn
Shawn

Reputation: 734

Listing page always returned a exception for asking provide id

I'm using ASP.NET MVC + WEB API 2, with self host.

This is my self host 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);
    }
}

already specified the id is optional, but when accessing url:

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

always prompt error:

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.

this is the Controller:

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)
    {
        ...
    }
}

While testing result is correct with the detail page by url:

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

anyone could help?

Upvotes: 0

Views: 49

Answers (1)

Jia Jian Goi
Jia Jian Goi

Reputation: 1423

Change UrlParameter.Optional to RouteParameter.Optional. The former is for standard ASP.NET MVC whereas the latter is for ASP.NET Web API. They behave differently.

Just tested with a newly created Web API project, I am getting the exact same error as you if I use UrlParameter.Optional, but not when it is switched to RouteParameter.Optional.

See this SO answer Should I use RouteParameter or UrlParameter for an Asp.NET web-api route?

Upvotes: 1

Related Questions