非常感谢你的回答我的问题,因为我在asp.net很新,我真的很感激如何使用会话来避免某些用户查看某些页面?
我有一个会话身份用户在控制器
Session["UserId"] = UserNo;
Session["UserType"] = UserType;
我能如何避免用户如Session [“UserType”]为“3”,然后避免他/她登录到某些网页?
我需要在控制器中控制过滤器配置的视图?
非常感谢你的回答我的问题,因为我在asp.net很新,我真的很感激如何使用会话来避免某些用户查看某些页面?
我有一个会话身份用户在控制器
Session["UserId"] = UserNo;
Session["UserType"] = UserType;
我能如何避免用户如Session [“UserType”]为“3”,然后避免他/她登录到某些网页?
我需要在控制器中控制过滤器配置的视图?
创建一个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;
}
}
希望帮助,
哦,非常感谢,那太好了! @Berkay –
除了可能不是将这个逻辑放在构造中,而是使用['OnActionExecuting'覆盖](https://msdn.microsoft.com/zh-cn/library/system.web.mvc.controller.onactionexecuting( v = vs.118).aspx) – Reddog
我做了一个try catch方法,并且返回结果不起作用... 当我调试它时,它进入“return RedirectToAction ...”但没有路由到以下url catch { return RedirectToAction(“Index”,“Home”); } –
只要你有将用户重定向如果
public ActionResult Method()
{
if(Session["UserType"] = 3)
{
return View([forbidden page URL here]);
}
else
{
return View("controller/view");
}
}
希望它有助于。
'if(Session [“UserType”] = 3)'我想你需要修改这一行。 –
哎呀谢谢@ MAdeelKhalid我修改了它 –
我做了一个try catch方法,并且返回不起作用... 当我调试它时,它进入“return RedirectToAction ...”,但没有路由到以下url catch { return RedirectToAction(“Index”,“Home”); } –
您只需在每次用户尝试访问特定页面时检查会话值。
编辑: 试试这个
public ActionResult Details(int id)
{
var details = context.checkIfUserExist(userID);
if (details == null)
{
return RedirectToAction("takeHimSomewhere");
}
return View(details);
}
我做了一个try catch方法,并且返回不起作用... 当我调试它时,它进入“return RedirectToAction ...”但没有路由到以下url catch { return RedirectToAction(“Index”,“Home”); } –
@KeonVong - 请参阅我的编辑。 –
我建议不要在MVC上使用Response.Redirect。 [性能问题]。 –
而所有其他的答案是正确的,工作的,我想带领你解决这个问题,这也降低了代码的更多的“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
在控制器的操作方法,例如用'if'条件核对后仅仅对它们进行重定向if(Session [“UserId”] == 3){return RedirectToAction([禁止页面URL]); }' –
谢谢@TetsuyaYamamoto,我不知道答案很简单 –