【问题标题】:ASP.NET Web API Routing in ApiControllerApiController 中的 ASP.NET Web API 路由
【发布时间】:2013-08-04 02:57:39
【问题描述】:

我一直在为我的路由问题苦苦挣扎,几天后尝试谷歌解决方案没有运气,我希望有人能对我的问题有所了解。

我的 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?
  • 抱歉,我已经包含了失败的详细信息。

标签: asp.net-mvc asp.net-web-api asp.net-web-api-routing asp.net-mvc-controller


【解决方案1】:

你应该可以有以下路线:

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")] 存在。你能详细说明一下吗?或者甚至提供一个我可以阅读的链接?
  • 属性FromUriFromBody 告诉Web API 2 在哪里解析出参数。对于FromUri,它会解析出查询字符串并获取相应的命名值。
【解决方案2】:

您是否有理由需要声明两条不同的路线?

查看指南:http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

他们有一个默认路由,通过示例,您在配置中所需要的只是

routes.MapHttpRoute(
    name: "API Default",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-28
    • 1970-01-01
    • 2017-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多