建议在控制器和扩展方法访问ASP.NET MVC会议[]的数据? [英] Suggestions for Accessing ASP.NET MVC Session[] Data in Controllers and Extension Methods?

查看:102
本文介绍了建议在控制器和扩展方法访问ASP.NET MVC会议[]的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做一个ASP.NET MVC应用程序,我的一些行动方法和其他扩展方法需要访问的用户数据。在code我使用来获取用户的是:

I'm doing an ASP.NET MVC application and some of my Action Methods and other Extension Methods need access to User data. The code I'm using to get the user is:

this.currentUser = (CurrentUser)HttpContext.Session["CurrentUser"];

//and in the extension methods it's:

CurrentUser user = (CurrentUser)HttpContext.Current.Session["CurrentUser"];

这同一条线路分散在很多我的控制器有很多我的行动方法之一。问题是这样的使得难以检测,并且它不会出现是非常雅致。

This same line is scattered among a lot of my Action Methods in a lot of my Controllers. The problem is this makes it difficult to test, and it doesn't appear to be very 'elegant'.

任何人都可以提出一个良好的坚实的方法来解决这个?

can anyone suggest a good SOLID approach to this solution?

感谢

戴夫

推荐答案

您不应该存储用户会话中。会话可以当应用程序由在web.config中修改或到达存储器限制重新开始很容易丢失。这将在随机的时刻注销用户。

You shouldn't store user in Session. Session can be easily lost when application is restarted by modification in web.config or by reaching memory limit. This will log out user in random moments.

有什么理由不使用会话用于不同的目的(例如存储在篮中的物品)。你能做到这样的:

There is no reason not to use session for different purposes (for example to store items in basket). You can do it like that:

首先我们定义接口:

public interface ISessionWrapper
{
    int SomeInteger { get; set; }
}

然后我们做的HttpContext执行:

Then we make HttpContext implementation:

public class HttpContextSessionWrapper : ISessionWrapper
{
    private T GetFromSession<T>(string key)
    {
        return (T) HttpContext.Current.Session[key];
    }

    private void SetInSession(string key, object value)
    {
        HttpContext.Current.Session[key] = value;
    }

    public int SomeInteger
    {
        get { return GetFromSession<int>("SomeInteger"); }
        set { SetInSession("SomeInteger", value); }
    }
}

然后我们定义我们的基本控制器:

Then we define our base controller:

public class BaseController : Controller
{
    public ISessionWrapper SessionWrapper { get; set; }

    public BaseController()
    {
        SessionWrapper = new HttpContextSessionWrapper();
    }
}

最后:

public ActionResult SomeAction(int myNum)
{           
    SessionWrapper.SomeInteger
}

这会使测试很容易,因为你可以在控制器测试,模拟代替ISessionWrapper。

This will make testing easy, because you can replace ISessionWrapper with mock in controller tests.

这篇关于建议在控制器和扩展方法访问ASP.NET MVC会议[]的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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