【问题标题】:Unexpected Web API routing when the URL ends in a forward slash当 URL 以正斜杠结尾时出现意外的 Web API 路由
【发布时间】:2014-12-02 20:39:36
【问题描述】:

我正在使用 Web API 2,当 URL 以正斜杠结尾时,我看到了意外的路由行为。我的 Web API 配置如下所示。

    public void Configuration(IAppBuilder appBuilder)
    {
        HttpConfiguration webApiConfig = new HttpConfiguration();
        webApiConfig.MapHttpAttributeRoutes();
        webApiConfig.EnsureInitialized();

        appBuilder.UseWebApi(webApiConfig);
    }

在 WebApp.Start() 中,我传递了 URL http://host:port/configuration

我设置了两条路线。

    [Route("~/")]
    public object GetResourcesList()
    {
        return new List<string>() { "Resource 1", "Resource 2", "Resource n" };
    }

    [Route("~/{resourceName}")]
    public object GetResource(string resourceName)
    {
        return "Resource " + resourceName;
    }

如果我向 http://host:port/configuration/ 发出 GET 请求,它会按预期调用 GetResourceList()

如果我向 http://host:port/configuration 发出 GET 请求(末尾没有正斜杠),它会调用 GetResource() 并返回“资源配置”。我希望它打电话给GetResourceList()

为什么在第二个例子中调用GetResource()?当 WebApp.Start 应该监听 http://host:port/configuration 而不是 http://host:port 时,为什么它会将配置作为 resourceName 传递?

我还分别为GetResourceList()GetResource() 尝试了[Route("")][Route("{resourceName}")],并看到了相同的行为。

感谢您的帮助。

编辑

我也刚刚尝试在http://host:port/configuration/ 上收听(末尾带有斜线)。行为上没有区别。

【问题讨论】:

    标签: c# asp.net-web-api asp.net-web-api2 asp.net-web-api-routing


    【解决方案1】:

    我没有弄乱 OWIN 自托管的东西,但我的猜测是它正在侦听您提供的 URI,但仍在传递整个 URL,即 Route 拾取的路径与您提供的 URI。

    我会从

    更改您的属性路由
    [Route("~/")]
    

    [Route("~/{resourceName}")]
    

    [Route("configuration")]
    

    [Route("configuration/{resourceName}")]
    

    或使用路由前缀

    [RoutePrefix("configuration")]
    

    【讨论】:

    • 这会引发 ArgumentException “路由模板不能以 '/' 或 '~' 字符开头,并且不能包含 '?'特点”。使用波浪号更像是最后一次尝试。我确实尝试过 [Route("")],我认为这与您的建议等效。
    猜你喜欢
    • 1970-01-01
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 2016-05-04
    相关资源
    最近更新 更多