Web API 2需要斜杠以使自定义属性路由正常工作 [英] Web API 2 requires trailing slash for custom attribute routing to work

查看:210
本文介绍了Web API 2需要斜杠以使自定义属性路由正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个Web API 2项目,尽管这些API可以正常工作,但是我必须输入一个斜杠以使它们能够这样做.

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.

这将产生404

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

这显示了预期的JSON响应

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...

似乎与十进制类型有关,好像我对URL进行了一些细微改动并使用了一个参数,API返回的结果没有问题:

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:

此变体还会按预期显示JSON响应

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

这不是世界末日,但我还使用Swagger生成了我的API文档,该文档自动使用了上面的第一个URL,并包含了内置测试,这些测试当然会失败.对于任何引用API文档的开发人员来说,这都不是很好.

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?

路由配置

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

自定义属性和控制器操作

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

推荐答案

使用 runAllManagedModulesForAllRequests .没有它,IIS认为它是一个文件请求,扩展名是小数点后的数字部分.找不到文件,404.

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

这篇关于Web API 2需要斜杠以使自定义属性路由正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆