0

我所有的控制器在类的顶部都有这个代码。

public class TestController : Controller
{
//
// GET: /Reports/

string userName;
string uid;
string accountType;
int companyCode;

protected override void Initialize(RequestContext requestContext)
{
    base.Initialize(requestContext);

    string cookieName = FormsAuthentication.FormsCookieName;
    HttpCookie authCookie = Request.Cookies[cookieName];


    if (authCookie != null)
    {
    FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
    string userData = authTicket.UserData;

    JavaScriptSerializer serializer = new JavaScriptSerializer();
    var userInfo = serializer.Deserialize<MemberModel>(userData);

    userName = userInfo.firstName + " " + userInfo.lastName;
    uid = userInfo.uid;
    accountType = userInfo.accountType;
    companyCode = userInfo.companyCode;
    }
}

因为,每个控制器都需要有 cookie 中的用户信息。

我认为这不是在每个控制器中编写该代码的正确方法。

此外,即使我不能在我的模型中使用该方法。

base.Initialize(requestContext); <= 'object' does not contain a definition for 'Initialize'

所以,我想知道如何将该方法设置为 GLOBAL 变量以在任何控制器和模型中使用。

有知道的请指教~

[编辑]

在此处输入图像描述

谢谢!

[编辑]

我在 HomeController 中定义如上代码并尝试在 testController 中调用 userName。但它是空的。(错误现在消失了)

在测试控制器中,

[HttpGet]
public void test()
{
    Response.Write(MemberModelProvider.UserName);
    Response.Write(System.Web.HttpContext.Current.Items["UserName"]);
}

它什么也没打印...

我究竟做错了什么?

我非常感谢您的帮助!

4

3 回答 3

4

为控制器创建一个公共基类,并使所有实际的控制器都继承它

public abstract class BaseController : Controller
{
    protected readonly MemberModel Member;

    protected BaseController()
    {
        Member = getUserInfoFromCookie();
    }
}
public class TestController : BaseController
{
}
于 2012-06-20T05:48:58.417 回答
2

每次使用操作过滤器执行每个操作时,您都可以执行那段代码。你可以在这里找到更多信息

于 2012-06-20T03:23:30.390 回答
1

您可以将该信息放在 HttpContext.Items 中。该集合在请求期间存在,因此您不会在不同请求访问相同代码时遇到任何麻烦:

public abstract class AuthenticatedController : Controller
{

  protected override void Initialize(RequestContext requestContext)
  {
    base.Initialize(requestContext);

    string cookieName = FormsAuthentication.FormsCookieName;
    HttpCookie authCookie = Request.Cookies[cookieName];


    if (authCookie != null)
    {
    FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
    string userData = authTicket.UserData;

    JavaScriptSerializer serializer = new JavaScriptSerializer();
    var userInfo = serializer.Deserialize<MemberModel>(userData);
    MemberModelProvider.Current = userInfo;
    }
  }
}

public class HomeController :  AuthenticatedController {

    //Your actions here...
}

public class TestController :  AuthenticatedController {

    //Your actions here...
}

public class MemberModelProvider {
    public static MemberModel Current {
        get { return (MemberModel)HttpContext.Current.Items["CurrentMemberModel"];}
        set { HttpContext.Current.Items["CurrentMemberModel"] = value; }
    }
}

然后,只要您需要使用它,您只需调用MemberModelProvider.Current.

于 2012-06-20T05:59:27.577 回答