1

在我的代码中,我正在调用一个函数,该函数对数据库进行一些验证检查,如果它们失败,它应该将用户发送到“拒绝访问”页面......但似乎不起作用。

以前,重定向将使用 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

4

2 回答 2

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);
    }
}

我毫不怀疑代码可以改进,这是我将继续努力的方向,但这肯定是一个初学者。

于 2013-12-06T12:07:38.377 回答
0

RedirectToAction返回 a RedirectToRouteResult,因此您应该执行以下操作:

 public ActionResult MyPage()
 {
      // security
      if (failCheck)
         return RedirectToAction("NoAccess", "MyController");

      /*
        Do normal code
      */

      // Display page
      return View();
 }
于 2013-12-06T10:15:14.160 回答