locked
Missing optional routing argument not null RRS feed

  • Question

  • User-1982247078 posted

    Hi!

    I have a simple route with an optional "version" argument:

    routes.MapRoute(name: "pages", template: "{action=Index}/{version?}", defaults: new { Controller = "Pages" });

    and corresponding action method:

    public IActionResult Index(Version version = null) { ... }

    However, when I navigate to / the action method gets invoked with version = 0.0, not null. Where does that value come from and how can I fix that?

    Thanks!

    Monday, April 13, 2020 1:04 PM

Answers

All replies

  • User475983607 posted

    Where does that value come from and how can I fix that?

    Version looks like a complex type.  Most likely the actual property that holds the version is not a nullable type.  Secondly, I don;t think you can use a complex type as a route parameter.  How will the framework know which property to bind?

    See the standard routing docs.

    https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-3.1

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, April 13, 2020 2:21 PM
  • User-1982247078 posted

    mgebhard

    the actual property that holds the version is not a nullable type

    I am not quite sure what do you mean by the "actual property". There is no properties involved. `System.Version` is a reference type so I expect the default to be null. I even tried to specify it explicitly using

    routes.MapRoute(name: "pages", template: "{action=Index}/{version?}", defaults: new { Controller = "Pages", version = (Version)null });

    but nothing changed.

    mgebhard

    I don;t think you can use a complex type as a route parameter.

    Oh! I see what you are saying.. the framework treats the Version type as a container whose properties should be bound to the parameters, so it just instantiates it and then there is nothing to bind to.

    To answer your question I thought the framework would get the argument string value and try to convert it into an instance of Version (e.g. using Convert.ChangeType), but obviously that is not the case. Looks like to provide this functionality I need to utilize an action filter.

    Thank you!

    Monday, April 13, 2020 2:50 PM
  • User-1982247078 posted

    Actually the solution is much simpler, the framework already does what I expected it to do, however, there is no type converter registered for the Version class.

    The solution is to register one using TypeDescriptor.AddAttributes.

    Monday, April 13, 2020 5:05 PM