2017-10-18 116 views
0

我想设置一个控制器来使用2个不同的URL。MVC路由 - 多个URL匹配到单个控制器/方法

所以,我要的是导航到:

  • mysite.com/MyArea/some-route/SomeAction
  • mysite.com/OtherArea/some-route/SomeAction

并让他们都去同一个地方。

所以我有一个类设置是这样的:

[RouteArea("MyArea", AreaPrefix = "MyArea")] 
[RoutePrefix("some-route")] 
[Route("{action}")] 
public class MyController : Controller 
{ 
    [Route("SomeAction")] 
    [Route("~/OtherArea/some-route/SomeAction")] 
    [AcceptVerbs(HttpVerbs.Get)] 
    public ActionResult MyAction() 
    { 
     return View(); 
    } 
} 

所以此工程 - 尽管看起来有点凌乱。
我可以在浏览器中输入任意一个网址,它会选择这个动作/页面。

'OtherArea'并不存在。这只是有时我想使用第一个网址,有时是第二个网址。

1)如何路由到此操作并指定url?

RedirectToAction("MyAction", "MyController", new { area = "MyArea" }); 

我只指定控制器/操作 - 它自己找到的URL。 我可以强迫它使用其中一种吗?

理想情况下不用硬编码路径。

2)有没有更好的方法来做我想做的事情?
我不是这行的粉丝:

[Route("~/OtherArea/some-route/SomeAction")] 

但我也不想只为具有第二网址的缘故创建控制器的副本和新的区域。

感谢

回答

1

你应该把一个方法你的逻辑和2个不同模式操作

[Route("SomeAction")]  
[AcceptVerbs(HttpVerbs.Get)] 
public ActionResult MyAction1() 
{ 
    MyMethod() 
    return View("MyAction"); 
} 


[Route("~/OtherArea/some-route/SomeAction")] 
[AcceptVerbs(HttpVerbs.Get)] 
public ActionResult MyAction2() 
{ 
    MyMethod(); 
    return View("MyAction"); 
} 

private MyMethod(){ 
.... 
} 

使用它,但他们仍然可以有相同的看法

+0

嗯这实际上比我更简单期待。不知道我怎么没有想到这个> _ < –