在ASP.NET路由可选参数MVC 5 [英] Routing optional parameters in ASP.NET MVC 5

查看:298
本文介绍了在ASP.NET路由可选参数MVC 5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个ASP.NET MVC 5应用程序,我有与路由的一些问题。我们使用属性路线来我们在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...
}

我们,如果我们在网​​址,这样的结尾通过斜线字符 / 只能访问此网址

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 未找到错误,像这样

It works fine but does not work without /, I get a 404 not found error, like this

type/lib/version/file/cache

或本(无可选参数):

type/lib/version

我想在网​​址的末尾带有或不带有 / 字符访问。我最后的两个参数是可选的。

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();
    }
}

我该如何解决呢?使斜线 / 是可选呢?

推荐答案

也许你应该试着让你的枚举整型呢?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆