asp.net mvc -如何在c#中重定向

本文关键字:重定向 net mvc asp | 更新日期: 2023-09-27 17:54:11

在使用c#的MVC 3中,我想重定向某些未验证的方法。然而,这似乎不工作:

    private ActionResult m_VerifyLogin()
    {
        if (Session["isLogged"] == null || (int)Session["isLogged"] != 1)
        {
            return RedirectToAction("Index", "Home");
        }
        return View();
    }

有人知道我能做什么吗?即使我创建一个ActionFilterAttribute,我也希望它非常简单!

—EDIT—

谢谢你们的回答。我们尝试了一些你问的东西,然后我们在测试后想出了这个:

自定义ActionFilterAttribute:

public class IsLoggedAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Session["isLogged"] == null || (int) filterContext.HttpContext.Session["isLogged"] != 1)
        {
            filterContext.HttpContext.Response.RedirectToRoute(new { controller = "Home" });
        }
        base.OnActionExecuting(filterContext);
    }
}

我可以在路由方法上面抛出[IsLogged]

asp.net mvc -如何在c#中重定向

设置你的动作方法为public。你的代码看起来很好,因为重定向到另一个动作/控制器的动作方法可以通过RedirectToAction方法从控制器基类返回。

public ActionResult m_VerifyLogin()
{
    if (Session["isLogged"] != null || (int)Session["isLogged"] != 1)
    {
        return RedirectToAction("Index", "Home");
    }
    return View();
}

你的if声明也有点奇怪。检查会话中的值是否为空,并使用OR逻辑运算符强制转换它(可能为空)以测试值。你可以试着这样做:

//If session value is not null then try to cast to int and check if it is not 1.
if (Session["isLogged"] != null || (int)Session["isLogged"] != 1)

如果Home控制器中的Index动作应用了ActionFilterAttribute,并且当前用户无效,您将获得重定向到表单认证配置中定义的登录页面。您还可以使用具有更好名称的操作方法名称来获得友好的url,例如VerifyLogin

public ActionResult VerifyLogin()
{
    if (Session["isLogged"] != null || (int)Session["isLogged"] != 1)
    {
        return RedirectToAction("Index", "Home");
    }
    return View();
}

RedirectToAction()返回一个RedirectToRouteResult对象,该对象告诉MVC在从操作返回它时发送一个重定向。

调用该方法而不使用其返回值将不会做任何事情。

您需要从操作本身返回您的私有方法的结果。