我正在创建一个 ASP.NET MVC 5 应用程序,但我遇到了一些路由问题。我们正在使用属性 Route
来映射我们在网络应用程序中的路线。我有以下操作:
[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,如下所示:
type/lib/version/file/cache/
它工作正常,但没有 /
就无法工作,我得到一个 404
not found 错误,就像这样
type/lib/version/file/cache
或者这个(没有可选参数):
type/lib/version
我想在 url
末尾使用或不使用 /
字符进行访问。我的最后两个参数是可选的。
我的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/
它工作正常...
关于c# - ASP.NET MVC 5 中的路由可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24678045/