RedirectToAction 路由后忽略区域
我有一个名为“Subscribers”的区域,该区域中有一个名为“SubscriptionsController”的控制器,具有两个公共操作方法:Index() 和 Unsubscribe(),其中 Unsubscribe() 方法传递一个订阅者 id,即 Unsubscribe(int id)
在某些情况下在某些情况下(例如 id 无效),Unsubscribe() 方法会对同一控制器上的其他操作执行 RedirectToAction("Index")。
public ActionResult Index()
{
return View();
}
如果我通过“/Subscribers/Subscriptions/Unsubscribe/999”访问该页面,RedirectToActionMethod() 会正确地将我重定向到 Index() 操作。
我希望能够“快捷”正式 url ('/Subscribers/Subscriptions/Unsubscribe/999'),因此我向 Global.ascx 文件添加了一条路由:
routes.MapRoute(
"Unsubscribe",
"Unsubscribe/{id}",
new {area = "Subscribers", controller = "Subscriptions", action = "Unsubscribe"}
);
该路由在运行 Unsubscribe() 方法时似乎可以正常工作正如预期的那样。我遇到的问题是 Unsubscribe() 中对 RedirectToAction("Index") 的调用现在失败,因为它们仍然调用正确的操作(Index()),视图引擎现在忽略该区域并尝试加载相对于网站的根目录 '~/Views/Subscriptions/Index.aspx' 而不是 '~/Areas/Subscribers/Views/Subscriptions/Index.aspx'
我可以通过修改Unsubscribe() 方法中的 RedirectToAction() 方法因此:
return RedirectToAction("Index", "Subscriptions", new { Area = "Subscribers" });
但这似乎是一个麻烦且不太灵活的问题解决方案。
任何建议或解释将不胜感激。
谢谢。
I have an Area named 'Subscribers' and a controller in that area named 'SubscriptionsController' with two public action methods: Index() and Unsubscribe() where the Unsubscribe() method is passed a subscriber id i.e. Unsubscribe(int id)
Under certain circumstances (the id is invalid for example), the Unsubscribe() method performs a RedirectToAction("Index") to the other action on the same controller.
public ActionResult Index()
{
return View();
}
if I access the page via '/Subscribers/Subscriptions/Unsubscribe/999' the the RedirectToActionMethod() correctly redirects me to the Index() action.
I wanted to be able to 'shortcut' the formal url ('/Subscribers/Subscriptions/Unsubscribe/999') so I added a route to the Global.ascx file:
routes.MapRoute(
"Unsubscribe",
"Unsubscribe/{id}",
new {area = "Subscribers", controller = "Subscriptions", action = "Unsubscribe"}
);
This route appears to work correctly as it runs the Unsubscribe() method as expected. The problem I have is the calls to RedirectToAction("Index") within Unsubscribe() now fail as they whilst they still invoke the correct action (Index()), the view engine now disregards the Area and tries to load a view relative to the root of the web site '~/Views/Subscriptions/Index.aspx' instead of '~/Areas/Subscribers/Views/Subscriptions/Index.aspx'
I can fix this by modifying the RedirectToAction() method in the Unsubscribe() method thus:
return RedirectToAction("Index", "Subscriptions", new { Area = "Subscribers" });
but this seems like a cumbersome and not very flexible solution to the problem.
Any advice or explanation would be much appreciated.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想我已经解决了这个问题。
路由需要进入Area的RegisterArea方法:
I think I have fixed the problem.
The routing needs to go in the Area's RegisterArea method: