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

馋奶兔 提交于 2020-01-02 02:37:06

问题


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;
    }

回答1:


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



来源:https://stackoverflow.com/questions/30739351/web-api-2-requires-trailing-slash-for-custom-attribute-routing-to-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!