gpt4 book ai didi

c# - ASP.NET MVC3 将 REST 服务路由到 Controller

转载 作者:太空狗 更新时间:2023-10-29 22:11:15 25 4
gpt4 key购买 nike

我想按以下方式路由 REST 服务 url:

/User/Rest/ -> UserRestController.Index()
/User/Rest/Get -> UserRestController.Get()

/User/ -> UserController.Index()
/User/Get -> UserController.Get()

所以基本上我在 url 中为 Rest 创建了一个硬编码异常。

我对 MVC 路由不是很熟悉。那么实现这一目标的好方法是什么?

最佳答案

无论你在哪里注册你的路由,通常在 global.ascx 中

        routes.MapRoute(
"post-object",
"{controller}",
new {controller = "Home", action = "post"},
new {httpMethod = new HttpMethodConstraint("POST")}
);

routes.MapRoute(
"get-object",
"{controller}/{id}",
new { controller = "Home", action = "get"},
new { httpMethod = new HttpMethodConstraint("GET")}
);

routes.MapRoute(
"put-object",
"{controller}/{id}",
new { controller = "Home", action = "put" },
new { httpMethod = new HttpMethodConstraint("PUT")}
);

routes.MapRoute(
"delete-object",
"{controller}/{id}",
new { controller = "Home", action = "delete" },
new { httpMethod = new HttpMethodConstraint("DELETE") }
);


routes.MapRoute(
"Default", // Route name
"{controller}", // URL with parameters
new { controller = "Home", action = "Index" } // Parameter defaults
,new[] {"ToolWatch.Presentation.API.Controllers"}
);

在你的 Controller 中

public ActionResult Get() { }
public ActionResult Post() { }
public ActionResult Put() { }
public ActionResult Delete() { }

关于c# - ASP.NET MVC3 将 REST 服务路由到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5868950/

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