Web API 2 requires trailing slash for custom attribute routing to work

3.2k views Asked by At

I have created a Web API 2 project and although the APIs work fine, I must enter a trailing slash for them to do so.

This results in a 404

http://www.myURL.com/api/v1/get/addressfromlatlong/UK/50.9742794/-0.1146699

This shows the JSON response as intended

http://www.myURL.com/api/v1/get/addressfromlatlong/UK/50.9742794/-0.1146699/

I have another controller with a custom action that works fine. The only difference is that this has one parameter that is an integer...

It seems to be something to do with the decimal type as if I make a slight variation in the URL and use a parameter, the API returns the results without issue:

This variation also shows the JSON response as intended

http://www.myURL.com/api/v1/get/addressfromlatlong/UK/50.9742794/?longitude=-0.1146699

It's not the end of the world but I also use Swagger to generate my API documentation and that automatically uses the first of the above URLs and includes built-in testing which, of course, fails. That's not so good for any developers who are referencing the API docs.

Can anyone explain why this may be happening and how I get it to work without the trailing slash?

Route Config

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapMvcAttributeRoutes();

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }

Custom attributes and Controller Action

[Route("get/addressfromlatlong/UK/{latitude:decimal=0}/{longitude:decimal=0}")]
    public AddressDetails GetAddressDetailsByLatLong(decimal latitude, decimal longitude)
    {
        AddressDetails addressDetails = repository.GetAddressDetailsByLatLong(latitude, longitude);
        return addressDetails;
    }
2

There are 2 answers

2
Alexander Polyankin On BEST ANSWER

Use runAllManagedModulesForAllRequests. Without it IIS thinks it is a file request with extension as number part after decimal point. File is not found, 404.

0
Papun Sahoo On

You can use the below code in your web.cong file:

<system.webServer>
 <modules runAllManagedModulesForAllRequests="true">
 </modules>
</system.webServer>