ASP.NET Core MVC之route简单路由配置
2019-02-14 10:47
961 查看
ASP.NET Core MVC的路由配置一般分为两种,约定路由和特性路由。下面分别介绍两种路由的配置方法。
一:约定路由
约定路由顾名思义,是我们约定好的路由规则,程序根据约定,访问对应的controller,首先建立一个ASP.NET Core Web项目,选择空模板,在Startup类中的ConfigureServices方法中注册MVC服务。
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); }
然后在Configure方法中使用mvc中间件,并添加路由规则
1.使用默认路由方法:
//默认mvc路由 //app.UseMvcWithDefaultRoute();
UseMvcWithDefaultRoute方法为默认路由,反编译源码如下:
public static IApplicationBuilder UseMvcWithDefaultRoute( this IApplicationBuilder app) { if (app == null) throw new ArgumentNullException(nameof (app)); return app.UseMvc((Action<IRouteBuilder>) (routes => routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}"))); }
我们由此可以看到,它的路由规则为默认home/index,id可为空,即如果url为localhost:2222/,那么他会默认寻找homeController的Index方法,当然如果url为localhost:/2222/about/me,那么他会访问aboutController的Me方法。
2.自定义路由规则
我们可以在mvc中间件中定义路由规则,代码如下:
app.UseMvc(builder => { //按约定配置路由 //Home/Index->HomeController Index(3) //默认值为Home,Index //builder.MapRoute("Default", "{controller=Home}/{action=Index}/{id?}"); });
如上,我们也可以设置默认值,但相对较灵活。
二.特性路由
我们可以在Controller文件中利用attribute特性配置路由,例:
[Route("")]//特性配置路由,留空为默认访问此Controller public class AboutController { [Route("")]//特性配置路由,留空为默认访问此action public string Me() { return "mike"; } [Route("company")] public string Company() { return "no company"; } }
如上代码,AboutController的route内容为“”,即为默认访问次controller,action同理,如不设置默认,则可加上名称,即
[Route("about")]//特性配置路由,留空为默认访问此Controller public class AboutController { [Route("me")]//特性配置路由,留空为默认访问此action public string Me() { return "mike"; } [Route("company")] public string Company() { return "no company"; } }
这样,url为localhost:2222/about/me就能访问此controller的me方法。
更为灵活的配置如下:
[Route("[controller]/[action]")]//特性配置路由, public class OtherController { public string Me() { return "zfy"; } public string Company() { return "no company"; } }
如此配置,程序会根据url来寻找对应的controller和action。
一般webapi会用特性路由配置。
注意:两种配置方法不能共存,只能选用一种。
相关文章推荐
- 史上最全的ASP.NET MVC路由配置,以后RouteConfig再弄不懂神仙都难救你啦~
- ASP.NET Core中使用默认MVC路由的配置
- 史上最全的ASP.NET MVC路由配置,以后RouteConfig再弄不懂神仙都难救你啦~ - Cherbim
- ASP.NET MVC路由配置(转载自http://www.cnblogs.com/zeusro/p/RouteConfig.html )
- 史上最全的ASP.NET MVC路由配置,以后RouteConfig再弄不懂神仙都难救你啦
- Asp.Net Core + Ocelot 网关搭建:路由简单配置
- 最全的ASP.NET MVC路由配置,以后RouteConfig再弄不懂去吃翔
- 史上最全的ASP.NET MVC路由配置,以后RouteConfig再弄不懂神仙都难救你啦~
- 史上最全的ASP.NET MVC路由配置,以后RouteConfig再弄不懂神仙都难救你啦~
- 史上最全的ASP.NET MVC路由配置,以后RouteConfig再弄不懂神仙都难救你啦~
- ASP.NET MVC路由匹配检测组件RouteDebug.dll
- ASP.NET MVC路由匹配检测组件RouteDebug.dll
- asp.net mvc 错误路由默认配置
- ASP.NET MVC路由匹配检测组件RouteDebug.dll
- ASP.NET MVC路由配置
- ASP.NET MVC路由配置
- ADO.NET .net core2.0添加json文件并转化成类注入控制器使用 简单了解 iTextSharp实现HTML to PDF ASP.NET MVC 中 Autofac依赖注入DI 控制反转IOC 了解一下 C# AutoMapper 了解一下
- 在ASP.NET Core MVC中构建简单 Web Api
- asp.Net Core免费开源分布式异常日志收集框架Exceptionless安装配置以及简单使用图文教程
- ASP.NET MVC 路由配置 管线模式伪静态