在我的代码中,我正在调用一个函数,它对数据库进行一些验证检查,如果它们失败,它应该将用户发送到“拒绝访问”页面......但似乎不起作用。< / p>
以前,重定向是使用Server.Transfer或Response.Redirect,但不确定如何使用MVC实现正确的效果。
简化,我的代码看起来像这样,任何帮助将不胜感激
private void CheckSecruity()
{
// secruity checks here
if (failCheck)
RedirectToAction("NoAccess", "MyController");
// if code gets here, security was passed
}
public ActionResult MyPage()
{
// Call Security Function
CheckSecruity();
/*
Do normal code
*/
// Display page
return View();
}
运行代码时会进入CheckSecurity()函数,但无论代码是什么,始终都会显示MyPage
答案 0 :(得分:1)
非常感谢Stijn的指导;已经调查过,这是完美的!我认为我会分享我所做的结果,因为它与使用MVC角色略有不同......
[MyNewSecurity]
public ActionResult MyPage()
{
return View();
}
我在该文件夹中添加了FILTERS文件夹和一个新的(SecurityAttribute.cs)类,其中包含以下代码(道歉,我必须删除一些)。
public class MyNewSecurityAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
// I may not need this; as I could still use the original [Authorize] on MyPage()
if (!httpContext.Request.IsAuthenticated)
return false;
// Area/Controller/Action
// Controller/Action
// Controller [default for index]
var path = httpContext.Request.CurrentExecutionFilePath
var structure = path.Split(new[] {"/"}, StringSplitOptions.RemoveEmptyEntries);
var sAreaName = "";
var sControllerName = "";
var sActionsName = "";
switch (structure.Length)
{
case 1:
sController = structure[0];
sActions = "Index";
break;
case 2:
sController = structure[0];
sActions = structure[1];
break;
case 3:
sArea = structure[0];
sController = structure[1];
sActions = structure[2];
break;
default:
return false;
}
var menuKey = string.Format("menu_{0}_{1}_{2}", sArea, sController, sActions);
// Roles for the menu are named to the above format
return httpContext.User.IsInRole(menuStructure);
}
}
我毫不怀疑代码可以改进,这是我将继续努力的方法,但这肯定是首发。
答案 1 :(得分:0)
您的RedirectToAction
会返回RedirectToRouteResult
,因此您应该执行以下操作:
public ActionResult MyPage()
{
// security
if (failCheck)
return RedirectToAction("NoAccess", "MyController");
/*
Do normal code
*/
// Display page
return View();
}