ASP.NET MVC 5 中的路由可选参数 [英] Routing optional parameters in ASP.NET MVC 5
问题描述
我正在创建一个 ASP.NET MVC 5 应用程序,但我在路由方面遇到了一些问题.我们使用属性 Route
来映射 Web 应用程序中的路由.我有以下操作:
I am creating an ASP.NET MVC 5 application and I have some issues with routing. We are using the attribute Route
to map our routes in the web application. I have the following action:
[Route("{type}/{library}/{version}/{file?}/{renew?}")]
public ActionResult Index(EFileType type,
string library,
string version,
string file = null,
ECacheType renew = ECacheType.cache)
{
// code...
}
我们只有在url
的末尾传递斜线字符/
才能访问这个URL,像这样:
We only can access this URL if we pass the slash char /
in the end of url
, like this:
type/lib/version/file/cache/
它工作正常,但没有 /
就不能工作,我得到一个 404
not found 错误,就像这样
It works fine but does not work without /
, I get a 404
not found error, like this
type/lib/version/file/cache
或者这个(没有可选参数):
or this (without optional parameters):
type/lib/version
我想在 url
的末尾使用或不使用 /
字符进行访问.我的最后两个参数是可选的.
I would like to access with or without /
char at the end of url
. My two last parameters are optional.
我的RouteConfig.cs
是这样的:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
}
}
我该如何解决?使斜杠 /
也是可选的吗?
How can I solve it? Make the slash /
be optional too?
推荐答案
也许您应该尝试将枚举改为整数?
Maybe you should try to have your enums as integers instead?
我就是这样做的
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 });
}
然后我可以像这样拨打电话
I can then make calls like
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/
它工作正常......
and it works fine...
这篇关于ASP.NET MVC 5 中的路由可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!