gpt4 book ai didi

ASP.NET Web API - 路由

转载 作者:行者123 更新时间:2023-12-04 05:15:21 24 4
gpt4 key购买 nike

我正在使用 Web API 来公开一堆服务。我在某些路线上遇到问题,需要一些帮助。

我定义了默认路由:

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new {id = RouteParameter.Optional}
);

通过这条路线,我可以访问正常路线,例如:“/api/clients/”和“/api/clients/4”。我想要一个命中以下路由“api/clients/4/profiles”和“api/clients/4/validations”的 GET。

我尝试了以下路线但没有成功:
config.Routes.MapHttpRoute(
name: "ClientProfilesApi",
routeTemplate: "api/{controller}/{clientid}/profiles",
defaults: new { action = RouteParameter.Optional },
constraints: new { controller = "clients" }
);

config.Routes.MapHttpRoute(
name: "ClientValidationsApi",
routeTemplate: "api/{controller}/{clientid}/validations",
defaults: new { action = RouteParameter.Optional },
constraints: new { controller = "clients" }
);

我还尝试使用“ActionName”属性,如下所示:
[HttpGet]
[ActionName("profiles")]
public IEnumerableResponseDto<ProfileLayoutDto> GetProfiles(Int64 clientId, [FromUri] IEnumerableRequestDto request)
{ .... }


[HttpGet]
[ActionName("profiles")]
public IEnumerableResponseDto<ValidationLayoutDto> GetValidations(Int64 clientId, [FromUri] IEnumerableRequestDto request)
{ .... }

我错过了什么?一个 Controller 中不能有多个 GET 吗?

最佳答案

对于路由“api/clients/4/profiles”和“api/clients/4/validations”,将操作命名为“profiles”和“validations”,然后在默认路由之前使用以下路由:

config.Routes.MapHttpRoute(
name: "ClientProfilesApi",
routeTemplate: "api/clients/{clientid}/profiles",
defaults: new { controller = "clients", action = "profiles", },
constraints: new {clientid = @"\d+" }
);

config.Routes.MapHttpRoute(
name: "ClientValidationsApi",
routeTemplate: "api/clients/{clientid}/validations",
defaults: new { controller = "clients", action = "validations", },
constraints: new {clientid = @"\d+" } );

这意味着路由“api/clients/4/profiles”转到 Controller “clients”和操作“profiles”,并且参数“clientid”必须是整数。

默认路由应该总是最后。

关于ASP.NET Web API - 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14350577/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com