c# - ASP.NET MVC 5 中的路由可选参数

标签 c# asp.net asp.net-mvc routing asp.net-mvc-5

我正在创建一个 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/

相关文章:

asp.net-mvc - 为什么 Entity Framework 不初始化我的导航集合?

c# - 将日期时间转换为 double

c# - TreeView(带有复选框)没有正确处理点击?

c# - 为什么在我的 ASP.Net 网站上大约每周一次出现 System.IO.FileLoadException : Could not load file or assembly,?

.net - ASP.Net MVC - 为什么要为 favicon.ico 创建 Controller ?

c# - ASP.NET MVC : Structuring Controllers

c# - Windows Phone 如何在后台运行应用程序?

c# - Quartz.NET - 这个单元测试不应该通过吗?

c# - 缺少表定义的 SQL 条件

c# - C# 中的属性或变量