Search code examples
asp.netasp.net-web-apiasp.net-mvc-routingasp.net-web-api-routingasp.net-routing

ASP.Net Web API Routing with optional parameters


I Have a Web API endpoint like something below -

[HttpPost]  
[ActionName("ResetPassword")]   
public HttpResponseMessage ResetPassword(string userName, string Template, string SubjectKey,[FromBody] Dictionary<string, string> KeyWords)

As you see, there are 4 parameters to the WebAPI. However, other than the first parameter 'userName', all other parameters are optional. All the parameters are of string type and as such by default nullable.

I have configured the route, using convention based routing (it's a legacy project).

Config.Routes.MapHttpRoute(
             name: "ResetPasswordResetV2",
             routeTemplate: "Email/ResetPassword",
             defaults: new { controller = "Email", action = "ResetPassword", routeValue = true });

I was expecting it to work with either -

http://{base address}/V2/Core/Email/ResetPassword?userName=hdhd@hshshs.com&template=&subjectKey=
http://{base address}/V2/Core/Email/ResetPassword?userName=hdhd@hshshs.com

Not working. I get a 404. Any tips what I am doing wrong. I have read all kind of SO and doc links and there looks to be too much information to process.

Additionally, what does this 'routeValue = true' means ?

Update : I got it working with the first URL but I would have expected it to work with the second API too. One more Info, my controller has one more Action with similar sets of input parameters but the action name is different (Can that in any way mess it up ?)


Solution

  • Try this:

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{userName}/{template}/{subjectKey}",
        defaults: new { controller = "Email", action = "ResetPassword", template = UrlParameter.Optional, subjectKey = UrlParameter.Optional 
    });
    

    Where, userName is required, but template and subjectKey are optional.

    URLs, will look like this (supoussing that template is equal to template1 and subjectKey is equal to 3):

    http://{base address}/V2/Core/Email/ResetPassword/hdhd@hshshs.com/template1/3
    

    Or, not having any params, only userName:

    http://{base address}/V2/Core/Email/ResetPassword/hdhd@hshshs.com
    

    If it's completely necessary, you can send information as query parameters, but you will have to indicate in Controller.

    URL typed:

    enter image description here

    Params received in Controller:

    enter image description here