为什么我的带有双args的Web API方法没有被调用?

B. *_*non 7 c# rest double asp.net-web-api-routing

我有一个Web API方法,需要两个双参数:

存储库界面:

public interface IInventoryItemRepository
{
. . .
    IEnumerable<InventoryItem> GetDepartmentRange(double deptBegin, double deptEnd);
. . .
}
Run Code Online (Sandbox Code Playgroud)

库:

public IEnumerable<InventoryItem> GetDepartmentRange(double deptBegin, double deptEnd)
{
    // Break the doubles into their component parts:
    int deptStartWhole = (int)Math.Truncate(deptBegin);
    int startFraction = (int)((deptBegin - deptStartWhole) * 100);
    int deptEndWhole = (int)Math.Truncate(deptEnd);
    int endFraction = (int)((deptBegin - deptEndWhole) * 100);

    return inventoryItems.Where(d => d.dept >= deptStartWhole).Where(e => e.subdept >= startFraction)
        .Where(f => f.dept <= deptEndWhole).Where(g => g.subdept >= endFraction);
}
Run Code Online (Sandbox Code Playgroud)

控制器:

[Route("api/InventoryItems/GetDeptRange/{BeginDept:double}/{EndDept:double}")]
public IEnumerable<InventoryItem> GetInventoryByDeptRange(double BeginDept, double EndDept)
{
    return _inventoryItemRepository.GetDepartmentRange(BeginDept, EndDept);
}
Run Code Online (Sandbox Code Playgroud)

当我尝试调用此方法时,通过:

http://localhost:28642/api/inventoryitems/GetDeptRange/1.1/99.99
Run Code Online (Sandbox Code Playgroud)

...我得到了," HTTP错误404.0 - 未找到您要查找的资源已被删除,其名称已更改,或暂时不可用. "

相关方法运行正常(此Controller上的其他方法).

Joe*_*oel 16

我能够在我的机器上重现这一点.

只需在URL的末尾添加一个/就更正了.看起来路由引擎将其视为.99文件扩展名,而不是输入参数.

http://localhost:28642/api/inventoryitems/GetDeptRange/1.1/99.99/
Run Code Online (Sandbox Code Playgroud)

此外,看起来您可以注册一个自定义路由,在使用内置帮助程序生成链接时,会自动在URL的末尾添加尾部斜杠.我没有亲自测试过: stackoverflow在每个url的末尾添加一个尾部斜杠

最简单的解决方案是将以下行添加到RouteCollection中.不确定如何使用该属性,但在RouteConfig中,您只需添加以下内容:

routes.AppendTrailingSlash = true;
Run Code Online (Sandbox Code Playgroud)


Ant*_*t P 7

正如Joel所指出的,这可能是IIS在文件扩展名上获取并尝试提供静态文件.您可以通过将以下内容添加到web.config文件(下system.webServer)来解决此问题:

<modules>
    <remove name="UrlRoutingModule-4.0" />
    <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule"
               preCondition="" />
</modules>
Run Code Online (Sandbox Code Playgroud)

默认情况下,IIS只会针对它认为是ASP.NET资源的请求运行此模块 - 上面会基于每个站点删除此条件,允许您通过ASP.NET MVC/Web API路由路由所有请求.

静态文件仍然是首选,如果它们存在,所以这不应该导致其他地方的任何问题.