2017-07-17 84 views
0

我需要創建一個自定義操作過濾器屬性,其中包含2個「RouteAttibute」過濾器的聲明。包含2個路由屬性過濾器的MVC自定義過濾器

我需要:

[Contains2Routes] 
public ActionResult Index() 
{ 
    return View(); 
} 

相反的:

[Route("~/index1")] 
[Route("~/index2")] 
public ActionResult Index() 
{ 
    return View(); 
} 

謝謝你的助手!

回答

0

可能是不做到這一點的最好辦法,但你可以做到這一點與自定義路由屬性那樣:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = false)] 
public sealed class MultiRouteAttribute : Attribute, IDirectRouteFactory 
{ 
    public string Name { get; set; } 

    public int Order { get; set; } 

    public string[] Templates { get; private set; } 


    public MultiRouteAttribute(string[] template) 
    { 
     this.Templates = template; 
    } 

    RouteEntry IDirectRouteFactory.CreateRoute(DirectRouteFactoryContext context) 
    { 
     var template = "~/{Type:regex(" + string.Join("|", Templates) + ")}"; 
     IDirectRouteBuilder builder = context.CreateBuilder(template); 
     builder.Name = this.Name; 
     builder.Order = this.Order; 
     return builder.Build(); 
    } 
} 

而且你可以用它這樣的:

[MultiRoute(new[] { "index1", "index2" })] 
public ActionResult Index() 
{ 
    return View(); 
} 

相反的:

[Route("~/index1")] 
[Route("~/index2")] 
public ActionResult Index() 
{ 
    return View(); 
} 

該解決方案是比較有限的比內置RouteAttribute,因爲它只是在路由中使用正則表達式

+0

首先感謝,第二,如果我想添加參數,默認值和約束,該怎麼辦? –