我正在创建一个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结尾处通过斜杠字符/,我们才能访问此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.Ign或eRoute("{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/

and it w或ks fine...

Asp.net相关问答推荐

如何从 Azure 上托管的应用服务获取登录用户名?

如何在 Javascript 中获取 C# 枚举

在 lambda 表达式中否定 Func

返回 JSON 对象 (ASP.NET WebAPI)

用户NT AUTHORITY\NETWORK SERVICE登录失败

无法加载文件或程序集 'System.Web.Mvc,版本 = 3.0.0.0,Elmah.MVC 问题

使用 ASP.NET WebForms 的 jQuery DataTables 服务器端处理

上传时验证大文件

ASP.NET 中的 <% %>(嵌入式代码块)

使用 LINQ 进行递归控制搜索

存在 ios 7 虚拟键盘时,div 元素不会停留在底部

什么是实体框架中的复杂类型以及何时使用它?

aspnet_compiler 发现错误版本的 System.Web.WebPages 1.0.0.0 而不是 2.0.0.0

<%# Eval("State") %> 或 <%# DataBinder.Eval(Container.DataItem, "state")%>

GMT 和 UTC 一样吗?

将列表转换为 json 格式 - 快速简便的方法

在c#中显示带有换行符的标签文本

如何使用 jquery 设置单选按钮 Select 的值

从服务器下载 ASP.NET 文件

您将如何将 ASP.Net MVC 嵌入到现有的网站项目中?