[英]ASP.NET MVC5: RedirectToAction
I want that if the user doesn't have access to a specific page, the will redirect to this page "ErrorAccessPage.cshtml" . 我希望如果用户无权访问特定页面,则会重定向到此页面“ErrorAccessPage.cshtml” 。 This page doesn't have any controller. 此页面没有任何控制器。 It is in the Folder name Shared . 它位于文件夹名称Shared中 。
Here's the logic: 这是逻辑:
if (user has access){
return View();
}
else
{
return RedirectToAction("//how to input the page here?");
}
Update: 更新:
After I changed the code to this: 我将代码更改为:
if (moduleViewModel.CanRead == true){
return View();
}
else
{
return RedirectToAction("~/Shared/ErrorAccessPage.cshtml");
}
You can't RedirectToAction
without a controller, since the Action must live on a controller. 没有控制器,您不能RedirectToAction
,因为Action必须存在于控制器上。 That said, you can redirect to a "plain" html file: 也就是说,您可以重定向到“普通”html文件:
Redirect("~/Shared/ErrorAccessPage.html");
or you can return the view directly from your current controller action without redirecting at all: 或者您可以直接从当前控制器操作返回视图,而无需重定向:
return View("~/Shared/ErrorAccessPage.cshtml");
As for your updated error message, since you are trying to access a view outside of the Views folder, MVC is prohibiting the serving up of the file. 至于您更新的错误消息,因为您尝试访问Views文件夹之外的视图,MVC禁止提供该文件。 You have two options: 您有两种选择:
Move the view inside of the views folder: 移动视图文件夹内的视图:
return View("~/Views/Shared/ErrorAccessPage.cshtml");
Allow MVC to serve up views from outside of the Views folder by adding: 通过添加以下内容,允许MVC从Views文件夹外部提供视图:
<add key="webpages:Enabled" value="true" />
to your web.config 到你的web.config
For security and consistency reasons, the former is recommended. 出于安全性和一致性原因,建议使用前者。
You can use method View("ErrorAccessPage")
to show your page. 您可以使用方法View("ErrorAccessPage")
来显示您的页面。
RedirectToAction()
will be search for a controller action not a view. RedirectToAction()
将搜索控制器操作而不是视图。 If it find a controller action it passes the execution control to that matched controller action. 如果找到控制器操作,它会将执行控制传递给匹配的控制器操作。
If you want to just show a view you can use View("view_name")
. 如果您只想显示视图,可以使用View("view_name")
。 Because it will search a html, aspx or cshtml file under the directory View->Your_Current_Controller_Name and View->Shared in your solution and just display it. 因为它将在您的解决方案中的View-> Your_Current_Controller_Name和View-> Shared目录下搜索html,aspx或cshtml文件并显示它。
if (user has access){
return View();
}
else
{
return View("ErrorAccessPage");
}
So, your final code will be, 那么,你的最终代码将是,
Hope this will help you. 希望这会帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.