加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – ApiController中的ASP.NET Web API路由

发布时间:2020-12-16 06:32:39 所属栏目:asp.Net 来源:网络整理
导读:我一直在努力使用我的路由已经有一段时间了,经过几天尝试谷歌解决方案没有运气,我希望有人能够对我的问题有所启发. 我的WebApiConfig中有以下路由: config.Routes.MapHttpRoute( name: "AccountStuffId",routeTemplate: "api/Account/{action}/{Id}",defaul
我一直在努力使用我的路由已经有一段时间了,经过几天尝试谷歌解决方案没有运气,我希望有人能够对我的问题有所启发.

我的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}",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]装饰是我在谷歌上发现的一部分,但它们似乎没有解决这个问题.

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

编辑:

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

<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>

解决方法

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

config.Routes.MapHttpRoute(
        name: "AccountStuffId",Id = RouteParameter.Optional }
    );

并执行以下操作:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读