簡體   English   中英

ASP.NET MVC 5 中的路由可選參數

[英]Routing optional parameters in ASP.NET MVC 5

我正在創建一個 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末尾使用或不使用/ char 進行訪問。 我的最后兩個參數是可選的。

我的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/

它工作正常......

//its working with mvc5
[Route("Projects/{Id}/{Title}")]
public ActionResult Index(long Id, string Title)
{
    return view();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM