【问题标题】:MVC Routing - multiple url's matching to a single controller/methodMVC 路由 - 多个 url 匹配单个控制器/方法
【发布时间】:2017-10-18 14:32:43
【问题描述】:

我正在尝试设置一个控制器来使用 2 个不同的 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();
    }
}

所以这行得通 - 虽然看起来有点乱。
我可以在浏览器中输入任何一个 URL,它会选择这个动作/页面。

“其他区域”并不存在。只是有时我想使用第一个 url,有时是第二个。

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

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

我只是指定控制器/动作——它自己找到的 URL。 我可以强制它使用其中一个吗?

最好不要硬编码路径。

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

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

但我也不想仅仅为了拥有第二个 url 而创建控制器和新区域的副本。

谢谢

【问题讨论】:

    标签: c# .net asp.net-mvc asp.net-mvc-5


    【解决方案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(){
     ....
    }
    

    但他们仍然可以共享相同的视图

    【讨论】:

    • 嗯,这实际上比我预期的要简单得多。不知道我怎么没想到>_
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2013-07-24
    • 1970-01-01
    相关资源
    最近更新 更多