ApiController中的ASP.NET Web API路由

Mik*_*ike 4 asp.net-mvc asp.net-mvc-controller asp.net-web-api asp.net-web-api-routing

我一直在努力使用我的路由已经有一段时间了,经过几天尝试谷歌解决方案没有运气,我希望有人能够对我的问题有所启发.

我的WebApiConfig中有以下路由:

        config.Routes.MapHttpRoute(
            name: "AccountStuffId",
            routeTemplate: "api/Account/{action}/{Id}",
            defaults: new { controller = "Account", Id = RouteParameter.Optional }
        );

        config.Routes.MapHttpRoute(
            name: "AccountStuffAlias",
            routeTemplate: "api/Account/{action}/{Alias}",
            defaults: new { controller = "Account", Alias = RouteParameter.Optional }
        );
Run Code Online (Sandbox Code Playgroud)

以及以下控制器方法:

    [HttpGet]
    public Account GetAccountById(string Id)
    {
        return null;
    }

    [HttpGet]
    public Account GetAccountByAlias(string alias)
    {
        return null;
    }
Run Code Online (Sandbox Code Playgroud)

如果我打电话: /API/Account/GetAccountById/stuff那么它正确调用GetAccountById.

但如果我打电话,/API/Account/GetAccountByAlias/stuff那么没有任何反应

显然,这里的顺序很重要,因为如果我在WebApiConfig中切换我的路由声明,那么/API/Account/GetAccountByAlias/stuff正确调用GetAccountByAlias,/API/Account/GetAccountById/stuff什么都不做.

这两个[HttpGet]装饰是我在谷歌上发现的一部分,但它们似乎没有解决问题.

有什么想法吗?我做了什么明显错误的事吗?

编辑:

当路由失败时,页面显示以下内容:

<Error>
    <Message>
        No HTTP resource was found that matches the request URI 'http://localhost:6221/API/Account/GetAccountByAlias/stuff'.
    </Message>
    <MessageDetail>
        No action was found on the controller 'Account' that matches the request.
    </MessageDetail>
</Error>
Run Code Online (Sandbox Code Playgroud)

Kir*_*lla 6

您应该能够拥有以下路线:

config.Routes.MapHttpRoute(
        name: "AccountStuffId",
        routeTemplate: "api/Account/{action}/{Id}",
        defaults: new { controller = "Account", Id = RouteParameter.Optional }
    );
Run Code Online (Sandbox Code Playgroud)

并执行以下操作:

[HttpGet]
public Account GetAccountById(string Id)
{
    return null;
}

[HttpGet]
public Account GetAccountByAlias([FromUri(Name="id")]string alias)
{
    return null;
}
Run Code Online (Sandbox Code Playgroud)