在ASP.NET MVC 5中路由可选参数
我正在创建一个ASP.NET MVC 5应用程序,我遇到了一些路由问题。 我们使用属性Route
来映射Web应用程序中的路由。 我有以下行动:
[Route("{type}/{library}/{version}/{file?}/{renew?}")] public ActionResult Index(EFileType type, string library, string version, string file = null, ECacheType renew = ECacheType.cache) { // code... }
如果我们在url
的末尾传递斜杠char /
,我们只能访问此URL,如下所示:
type/lib/version/file/cache/
它工作正常,但没有/
没有工作,我得到404
未找到错误,像这样
type/lib/version/file/cache
或者这个(没有可选参数):
type/lib/version
我想在url
的末尾使用或不使用/
char访问。 我的最后两个参数是可选的。
我的RouteConfig.cs
是这样的:
public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapMvcAttributeRoutes(); } }
我该如何解决? 斜杠/
也是可选的?
也许你应该尝试将你的枚举改为整数?
这就是我做到的
public enum ECacheType { cache=1, none=2 } public enum EFileType { t1=1, t2=2 } public class TestController { [Route("{type}/{library}/{version}/{file?}/{renew?}")] public ActionResult Index2(EFileType type, string library, string version, string file = null, ECacheType renew = ECacheType.cache) { return View("Index"); } }
和我的路由文件
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); // To enable route attribute in controllers routes.MapMvcAttributeRoutes(); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }); }
然后我就可以打电话了
http://localhost:52392/2/lib1/ver1/file1/1 http://localhost:52392/2/lib1/ver1/file1 http://localhost:52392/2/lib1/ver1
要么
http://localhost:52392/2/lib1/ver1/file1/1/ http://localhost:52392/2/lib1/ver1/file1/ http://localhost:52392/2/lib1/ver1/
它工作得很好……
//its working with mvc5 [Route("Projects/{Id}/{Title}")] public ActionResult Index(long Id, string Title) { return view(); }