2017-04-05 84 views
0

非常感谢你的回答我的问题,因为我在asp.net很新,我真的很感激如何使用会话来避免某些用户查看某些页面?

我有一个会话身份用户在控制器

Session["UserId"] = UserNo; 
    Session["UserType"] = UserType; 

我能如何避免用户如Session [“UserType”]为“3”,然后避免他/她登录到某些网页?

我需要在控制器中控制过滤器配置的视图?

+1

在控制器的操作方法,例如用'if'条件核对后仅仅对它们进行重定向if(Session [“UserId”] == 3){return RedirectToAction([禁止页面URL]); }' –

+0

谢谢@TetsuyaYamamoto,我不知道答案很简单 –

回答

2

创建一个BaseController以及您要检查用户的所有其他控制器应继承它。请求ActionResult之前,首先BaseController的构造会的工作,所以在BaseController构造函数,你可以做到这一点,

public BaseController() 
     { 
      try 
      { 
       int UserID = 0; 
       if (System.Web.HttpContext.Current.Session["UserId"] != null) 
        UserID = Convert.ToInt32(System.Web.HttpContext.Current.Session["UserId"]); 

       if (!(UserID > 0)) 
       { 
        System.Web.HttpContext.Current.Response.Redirect("controller/view"); 
       } 
      } 
      catch (Exception ex) 
      { 
       throw ex; 
      } 
     } 

希望帮助,

+0

哦,非常感谢,那太好了! @Berkay –

+0

除了可能不是将这个逻辑放在构造中,而是使用['OnActionExecuting'覆盖](https://msdn.microsoft.com/zh-cn/library/system.web.mvc.controller.onactionexecuting( v = vs.118).aspx) – Reddog

+0

我做了一个try catch方法,并且返回结果不起作用... 当我调试它时,它进入“return RedirectToAction ...”但没有路由到以下url catch { return RedirectToAction(“Index”,“Home”); } –

1

只要你有将用户重定向如果

public ActionResult Method() 
{ 
    if(Session["UserType"] = 3) 
    { 
    return View([forbidden page URL here]); 
    } 
    else 
    { 
    return View("controller/view"); 
    } 
} 

希望它有助于。

+1

'if(Session [“UserType”] = 3)'我想你需要修改这一行。 –

+0

哎呀谢谢@ MAdeelKhalid我修改了它 –

+0

我做了一个try catch方法,并且返回不起作用... 当我调试它时,它进入“return RedirectToAction ...”,但没有路由到以下url catch { return RedirectToAction(“Index”,“Home”); } –

1

您只需在每次用户尝试访问特定页面时检查会话值。

编辑: 试试这个

public ActionResult Details(int id) 
{ 
    var details = context.checkIfUserExist(userID); 
    if (details == null) 
    { 
     return RedirectToAction("takeHimSomewhere"); 
    } 
    return View(details); 
} 
+0

我做了一个try catch方法,并且返回不起作用... 当我调试它时,它进入“return RedirectToAction ...”但没有路由到以下url catch { return RedirectToAction(“Index”,“Home”); } –

+0

@KeonVong - 请参阅我的编辑。 –

+0

我建议不要在MVC上使用Response.Redirect。 [性能问题]。 –

1

而所有其他的答案是正确的,工作的,我想带领你解决这个问题,这也降低了代码的更多的“ASP-ISH”风格因为你不必在每个控制器中写一个if。

在ASP.NET中,有一个身份概念,它可以完全实现您想要手动存档的内容。 看看这里:https://docs.microsoft.com/de-de/aspnet/core/security/authentication/identity

一旦你实现了身份,你可以用[Authorize]标记你的控制器方法。

https://docs.microsoft.com/de-de/aspnet/core/security/authorization/introduction