Catch-all路由无法使用WebApi2 ApiController查找路由

Mat*_*eld 2 c# asp.net attributerouting asp.net-web-api2

我正在创建一个WebApi2服务,我想要实现的一个方法表示来自内部树结构中的对象的HTTP GET - 所以请求将是:

GET /values/path/path/to/object/in/tree
Run Code Online (Sandbox Code Playgroud)

所以我希望我的方法接收"path/to/object/in/tree".

但是,当我运行它时,我只得到404,而且有趣的是我得到的404与标准的IIS 404不同.它的标题是'/'应用程序中的'服务器错误',而完全无效的那个资源标题为'HTTP错误404.0 - 未找到'.

我正在玩默认模板试试看我是否可以使用它,因此相似性.

我有这个 RouteConfig

public static void RegisterRoutes(RouteCollection routes)
{
    var route = routes.MapRoute(
               name: "CatchAllRoute",
                url: "values/path/{*pathValue}",
                defaults: new { controller = "Values", action = "GetPath" });
}
Run Code Online (Sandbox Code Playgroud)

这是我的ValuesController:

[System.Web.Mvc.AuthorizeAttribute]
[RoutePrefix("values")]
public class ValuesController : ApiController
{
    [Route("test/{value}")]
    [HttpGet]
    public string Test(string value)
    {
        return value;
    }

    [HttpGet]
    public string GetPath(string pathValue)
    {
        return pathValue;
    }
}
Run Code Online (Sandbox Code Playgroud)

有趣的是,如果我派生Controller而不是ApiController它工作正常,但那么正常的属性路由不起作用.

我尝试按照这篇文章(http://www.tugberkugurlu.com/archive/asp-net-web-api-catch-all-route-parameter-binding)中的方法进行操作,但我无法使用它.

我敢肯定我错过了一些愚蠢的事情,但是花了几个小时才开始,我觉得谨慎地问我做错了什么.

谢谢

中号

cru*_*chy 5

Web api路由与路由MVC不同.代替

route.MapRoute
Run Code Online (Sandbox Code Playgroud)

尝试

public static void Register(HttpConfiguration config) {
    config.MapHttpAttributeRoutes

    config.Routes.MapHttpRoute(
        name: "CatchAll", routeTemplate: "values/path/{*pathvalue}", 
        defaults: new {id = RouteParameter.Optional });
}
Run Code Online (Sandbox Code Playgroud)

它从控制器工作的原因是MapRoute是路由MVC控制器的正确格式,而MapHttpRoute是为API控制器设计的.

  • 我觉得发誓.谢谢. (3认同)