简体   繁体   中英

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" . This page doesn't have any controller. It is in the Folder name 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. That said, you can redirect to a "plain" html file:

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. 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:

<add key="webpages:Enabled" value="true" />

to your web.config

For security and consistency reasons, the former is recommended.

You can use method View("ErrorAccessPage") to show your page.

RedirectToAction() will be search for a controller action not a view. 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") . 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.

if (user has access){
    return View();
}
else
{
    return View("ErrorAccessPage");
}

So, your final code will be,

Hope this will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM