如何在URL中更改ASP.NET MVC控制器名称?
如果我们有“example_name”,我们可以使用[ActionName(“”)]在url中更改它所以,我想为控制器名称执行此操作。
我可以做这个:
URL中的ControllerName> example_nameController >: “/ example_controller”
我想在URL中更改这样的控制器名称: “/ example-conroller”
您需要使用属性路由 ,这是MVC 5中引入的一项function。
根据您的示例,您应该按如下方式编辑控制器:
[RoutePrefix("example-name")] public class example_nameController : Controller { // Route: example-name/Index [Route] public ActionResult Index() { return View(); } // Route: example-name/Contact [Route] public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } }
使用控制器顶部的RoutePrefix
属性可以在整个控制器上定义路径。
如前所述,此function在MVC 5中原生可用,如果您使用的是以前版本的MVC,则需要添加以下NuGet包: AttributeRouting并在控制器中添加以下内容:
using AttributeRouting; using AttributeRouting.Web.Mvc;
如果您有另一个名为example_name2Controller
控制器,并且您想要添加链接到它的超链接,您可以轻松地按如下方式执行:
@Html.ActionLink("Go to example-name2", "Index", "example_name2");
您不需要调用将重定向到example_name2Controller
,但如果您需要在其他场合执行此操作,则可以这样执行:
public ActionResult RedirectToExample_Name2Controller() { return RedirectToAction("Index", "example_name2"); }
您可以通过Routes.cs
执行此Routes.cs
routes.MapRoute( name: "Controller", url: "example-controller/{action}", defaults: new { controller = "ControllerName", action ="Index" } );
还有另一种方法,如果你看一下这个问题的答案: 如何在ASP.NET MVC中实现动态控制器和动作方法?
user449689s答案很好,但他忘了提你需要补充
routes.MapMvcAttributeRoutes();
到RouteConfig.cs的RegisterRoutes()
您可以使用属性路由 。
[RoutePrefix("Users")] public class HomeController : Controller { //Route: Users/Index [Route("Index")] public ActionResult Index() { return View(); } }
您可以在Routes.cs中指定
routes.MapRoute( name: "College", url: "Student/{studentId}", defaults: new { controller = "Student", action = "Details"} );
我们可以将这样的约束定义为
上述就是C#学习教程:如何在URL中更改ASP.NET MVC控制器名称?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
routes.MapRoute( name: "College", url: "Student/{studentId}", defaults: new { controller = "Student", action = "Details"}, constraints:new{id=@"d+"} );
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/987900.html