如何在C#中重定向

JRE*_*EAM 1 c# asp.net-mvc asp.net-mvc-3

在使用C#的MVC 3中,我想重定向某些未经验证的方法.但是,这似乎不起作用:

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

        return View();
    }
Run Code Online (Sandbox Code Playgroud)

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

- 编辑 -

谢谢你们的所有答案.我们尝试了一些您提出的问题,然后我们在测试后想出了这个:

自定义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);
    }

}
Run Code Online (Sandbox Code Playgroud)

我可以将[IsLogged]抛到路由方法之上.

Fel*_*ani 5

制作你的行动方法public.您的代码看起来不错,因为要重定向到另一个操作/控制器,操作方法可以通过RedirectToActionController基类的方法返回.

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

你的if陈述也有点奇怪.您检查会话中的值是否为null,并使用OR逻辑运算符将其强制转换(可能为null)以使用值进行测试.你可以尝试做这样的事情:

//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)
Run Code Online (Sandbox Code Playgroud)

如果控制器中的Index操作HomeActionFilterAttribute应用且当前用户无效,您将获得重定向到表单身份验证配置中定义的登录页面.您还可以使用具有更好名称的操作方法名称来获取友好的URL,例如VerifyLogin.

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