如果用户直接访问ASP.Net MVC中的页面,如何重定向到登录页面

时间:2014-06-30 06:37:36

标签: asp.net-mvc-4 redirect global-asax

我在mvc中开发一个应用程序我的问题是在登录后它将重定向到某个页面。如果我复制网址并将其粘贴到另一个浏览器中它在应用程序中显示错误但我需要显示主页?

我试过这个

Global.asax中的

 protected void Session_Start(Object sender, EventArgs e)
    {

        Session["UserName"] = null;
        if (HttpContext.Current != null)
        {
            HttpContext.Current.Session.Add("CurrentCompany", "Company 1");
           // HttpContext.Current.Session.Add("Connectionstring", "");
        }
        if (Session["UserName"] == null)
        {
            HttpContext.Current.Session.Add("CurrentCompany", "Company 1");
           // Response.RedirectToRoute("Default");
            HttpContext.Current.Response.RedirectToRoute("Default", new { controller = "Login", action = "Create" });
        }
    }      

但它没有重定向我的问题与Response.RedirectToRoute("默认")或HttpContext.Current.Response.RedirectToRoute。

Plz帮帮我

1 个答案:

答案 0 :(得分:1)

  

这将有效

protected void Session_Start(Object sender, EventArgs e)
{

    Session["UserName"] = null;
    if (HttpContext.Current != null)
    {
        HttpContext.Current.Session.Add("CurrentCompany", "Company 1");
       // HttpContext.Current.Session.Add("Connectionstring", "");
    }
    if (Session["UserName"] == null)
    {
        HttpContext.Current.Session.Add("CurrentCompany", "Company 1");
        var routeData = new RouteData();
        routeData.Values["controller"] = "Login";
        routeData.Values["action"] = "Create";
        Response.StatusCode = 500;
        IController controller = new HomeController();
        var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
        controller.Execute(rc);
    }
}