ASP.NET Web API在ApiController中的路由

4

我一直在为我的路由问题苦苦挣扎,尝试了几天的谷歌搜索却没有找到解决方案,希望有人能为我的问题提供一些帮助。

以下是我在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 }
        );

以下是控制器方法:

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

    [HttpGet]
    public Account GetAccountByAlias(string alias)
    {
        return null;
    }

如果我调用: /API/Account/GetAccountById/stuff,那么它会正确地调用GetAccountById
但是如果我调用/API/Account/GetAccountByAlias/stuff,则什么也不发生。
显然,顺序很重要,因为如果我在我的WebApiConfig中切换路由的声明,则/API/Account/GetAccountByAlias/stuff会正确地调用GetAccountByAlias,而/API/Account/GetAccountById/stuff则什么也不做。
这两个[HttpGet]装饰是我在Google上找到的,但它们似乎无法解决问题。
有什么想法吗?我做错了什么吗?
编辑:
当路由失败时,页面显示以下内容:
<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>

你确定什么都没有发生还是实际上出现了404错误? - Tallmaris
抱歉,我已经包含了失败的细节。 - Mike
2个回答

6
您应该只需要以下路由:
config.Routes.MapHttpRoute(
        name: "AccountStuffId",
        routeTemplate: "api/Account/{action}/{Id}",
        defaults: new { controller = "Account", Id = RouteParameter.Optional }
    );

并为您的操作执行以下操作:
[HttpGet]
public Account GetAccountById(string Id)
{
    return null;
}

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

太好了!我不知道[FromUri(Name="id")]存在。你能详细介绍一下吗?或者给我提供一个链接让我自己读一下? - Mike
属性 FromUriFromBody 告诉 Web API 2 在哪里解析参数。对于 FromUri,它会解析查询字符串并获取相应的命名值。 - Cameron Tinker

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接