MVC中的会话变量 [英] session variables in MVC

查看:68
本文介绍了MVC中的会话变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用session [Admin] =从数据库中挑选的管理员的id,我已经为它指定了几个页面,如果此会话ID不为null,则允许查看页面但是如果它为null则不允许用户查看该页面,但问题是我在每个页面上执行此操作以检查它是否为null。有没有什么方法可以提及它并适用于所有应用程序?喜欢它是空的然后重定向到任何页面或这个页面。



i我正在使用mVC 3与asp.net 4 C#

解决方案

您可以使用表单身份验证在mvc中使用自定义成员资格,而不是使用会话变量。并且您可以在MVC中的控制器或操作方法上使用属性'[Authorize(Roles =Admin)]。如果用户不是管理员,则会自动重定向到登录页面。





自定义会员

 FormsAuthentication.SetAuthCookie(user.Id +& amp; quot。。& amp; quot; + role.Name, false ); 



受保护 void FormsAuthentication_OnAuthenticate( object sender,FormsAuthenticationEventArgs e)
{
if (FormsAuthentication.CookiesSupported == true
{
if (Request.Cookies [FormsAuthentication.FormsCookieName]!= < span class =code-keyword> null

{
string [] text =(FormsAuthentication.Decrypt($ b) $ b Request.Cookies [FormsAuthentication.FormsCookieName] .Value).Name)。Split(' 。' );
string userId = text [ 0 ];
string role = text [ 1 ];

e.User = new System.Security.Principal.GenericPrincipal( new System.Security.Principal.GenericIdentity(userId, Forms),role.Split(' ;'));
}
}
}







用法

 [授权(角色=   Admin)] 
public class AdminController:Controller
{
// action
}


i am using session["Admin"] = id of an admin picked from database, i have assigned few pages to it that if this session id is not null then allow to see pages but if it is null then don't allow user to view that page but problem is that i am doing this on every page to check if it is null or not. Is there any way to mention it once and work for all application ? like whenever it is empty then redirect to any page or this page.

i am using mVC 3 with asp.net 4 C#

解决方案

Instead of using Session Variables, you can use custom membership in mvc using Forms Authentication. And you can use the attribute '[Authorize(Roles = "Admin")] on controller or action methods in MVC. If user was not an admin then it automatically redirects to login page.


Custom Membership

FormsAuthentication.SetAuthCookie(user.Id + &amp;quot;.&amp;quot; + role.Name, false);



protected void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs e)
        {
            if (FormsAuthentication.CookiesSupported == true)
            {
                if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
                {
                    string[] text=(FormsAuthentication.Decrypt(
                        Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name).Split('.');
                    string userId = text[0];
                    string role = text[1];

                    e.User = new System.Security.Principal.GenericPrincipal(new System.Security.Principal.GenericIdentity(userId, "Forms"), role.Split(';'));
                }
            }
        }




Usage

[Authorize(Roles = "Admin")]
   public class AdminController : Controller
   {
//action 
}


这篇关于MVC中的会话变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆