你最喜欢的"当前用户QUOT; -pattern的Asp.net应用程序? [英] Your favorite "current user"-pattern for Asp.net applications?

查看:101
本文介绍了你最喜欢的"当前用户QUOT; -pattern的Asp.net应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是你所看到的,或用于访问登录的用户目前在Asp.NET应用的最好的模式?

What is the nicest pattern you have seen or used for accessing the current logged on user in an Asp.NET application?

当前用户指的是业务对象重新presents用户中的的系统,无论是会员的用户对象或自定义类。
用户对象应该很容易像全局(HttpApplication对象)的地方,Web表单,控制器,webhandlers等,这取决于它可能会被发送到项目的后端层,有时注入其他业务对象内到达的的应用程序。

Current user refers to the business object that represents a user in your system, be it a membership user object or a custom class. The user object should be easy to reach within places like global (httpapplication object), web forms, controllers, webhandlers etc. It is probably be sent to the back end layers of the project and sometimes injected in other business objects depending on your application.

要求:


  • 在这两个MVC和WebForms的工作很好。

  • 的模式应该能够要么ASPNET会员班或自己的类是用户的工作。

  • 打交道时不会被记录在清晰和明显的方式。

推荐答案

下面是我做的,而不是存储我觉得这不太有用的名称的对象。

Here's what I do to store an object instead of a name which I find less useful.

在我的帐户控制:

    public static User CacheUserInSession(User user)
    {
        Contract.Assert(user != null);

        if (user == null) // Not found, name may have changed
        {
            new FormsAuthenticationService().SignOut();
        }
        else
        {
            // Save off the user for later use by other classes
            ContextCache<User>.Set(user, ContextCache.AspNetUserSessionCache);
            ContextCache<int>.Set(user.RowId, ContextCache.UserIdSessionCache);
        }

        return user;
    }

    public static User GetUserFromSession()
    {
        var user = ContextCache<User>.Get(ContextCache.AspNetUserSessionCache);

        return user;
    }

我的缓存类:

public class ContextCache<T>
{    
    public static void Set(T objectToCache, string key)
    {
        System.Web.HttpContext.Current.Items.Add(key, objectToCache);
    }

    public static T Get(string key)
    {
        return (T)System.Web.HttpContext.Current.Items[key];
    }

}

我叫CacheUserInSession从Application_AuthenticateRequest传递我的用户对象/模型,我从数据库中读取。

I call CacheUserInSession from Application_AuthenticateRequest passing in my User object/model which I read from the database.

当我要检索的用户,我拨打这个电话:

When I want to retrieve the user, I make this call:

var user = AccountController.GetUserFromSession();

使用高速缓存的包装,可以存储/检索你想要的任何类型的对象。

Using the cache wrapper, you can store/retrieve any kind of object you want.

没有混乱。没有什么大惊小怪的。

No mess. No fuss.

这篇关于你最喜欢的&QUOT;当前用户QUOT; -pattern的Asp.net应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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