gpt4 book ai didi

rest - ASP.NET Web Api 路由自定义

转载 作者:行者123 更新时间:2023-12-03 23:22:04 24 4
gpt4 key购买 nike

我有以“Api”后缀结尾的 WebApi Controller (例如:StudentApiController、InstructorsApiController)。我这样做是为了轻松区分我的 MVC Controller 和 WebApi Controller 。我希望我的 WebApi 路由看起来类似于

http://localhost:50009/api/students/5 而不是 http://localhost:50009/api/studentsapi/5 .

目前为了实现这一目标,我正在设置类似的路线

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

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

这变得非常麻烦,因为我必须在我的 Controller 中为每个方法添加一个路由。我希望应该有一种简单的方法来设置路由模板,在处理路由时自动添加“api”后缀 Controller 名称。

最佳答案

按照@Youssef Moussaoui 的指导,我最终编写了以下代码来解决问题。

public class ApiControllerSelector : DefaultHttpControllerSelector
{
public ApiControllerSelector(HttpConfiguration configuration)
: base(configuration)
{
}

public override string GetControllerName(HttpRequestMessage request)
{
if (request == null)
throw new ArgumentNullException("request");

IHttpRouteData routeData = request.GetRouteData();

if (routeData == null)
return null;

// Look up controller in route data
object controllerName;
routeData.Values.TryGetValue("controller", out controllerName);

if (controllerName != null)
controllerName += "api";

return (string)controllerName;
}
}

并在 Global.asax 中注册为
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerSelector),
new ApiControllerSelector(GlobalConfiguration.Configuration));

关于rest - ASP.NET Web Api 路由自定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14484635/

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