在ASP.NET MVC中模拟User.Identity
|
我需要为一个ASP.NET MVC 2.0网站创建单元测试。该网站使用Windows身份验证。 我一直在阅读模拟处理HttpContext的代码的HTTP上下文的必要性。我觉得我也开始在DI模式上得到一个句柄。 (给类一个类型为IRepository的属性,然后在实例化控制器时传递Repository对象。) 然而,我不明白,是通过User.Identity Mock可用的Windows Principal对象的正确方法。这是HttpContext的这一部分吗? 任何机构都有一个链接到一个文章,演示这个(或一本书的建议)吗? 谢谢, Trey Carroll 解决方法我已经使用IoC来抽象这一点与一些成功。我首先定义了一个类来表示当前登录的用户:public class CurrentUser
{
public CurrentUser(IIdentity identity)
{
IsAuthenticated = identity.IsAuthenticated;
DisplayName = identity.Name;
var formsIdentity = identity as FormsIdentity;
if (formsIdentity != null)
{
UserID = int.Parse(formsIdentity.Ticket.UserData);
}
}
public string DisplayName { get; private set; }
public bool IsAuthenticated { get; private set; }
public int UserID { get; private set; }
}
它需要一个IIdentity在构造函数中设置其值。对于单元测试,您可以添加另一个构造函数,以允许绕过IIdentity依赖关系。 然后我使用Ninject(选择你最喜欢的IoC容器,没关系),并创建了一个IIdentity的绑定: Bind<IIdentity>().ToMethod(c => HttpContext.Current.User.Identity); 然后,在我的控制器里面我声明在构造函数中的依赖: CurrentUser _currentUser;
public HomeController(CurrentUser currentUser)
{
_currentUser = currentUser;
}
IoC容器看到HomeController接受一个CurrentUser对象,CurrentUser构造函数接受一个IIdentity。它将自动解决依赖关系,并中提琴!您的控制器可以知道当前登录的用户是谁。对于我来说,使用FormsAuthentication似乎工作得很好。您可能能够将此示例适用于Windows身份验证。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- .net – MVC – 是模型查看还是控制器查看?
- asp.net-mvc-4 – GAC问题不能在IIS上托管应用程序
- asp.net-mvc – 视图中的条件语句是坏消息吗?
- asp.net – C#:GDI:使用位图的保存方法过度写入图像
- 在ASP.NET MVC中搜索路径
- asp.net-mvc-3 – Structuremap,AutoFac或Ninject,哪一个适
- asp.net-mvc – 在MVC中修改密码4
- asp.net-mvc – 使用没有主键的查找在dbSet中查找记录
- asp.net – 在同一个域上的两个网站之间共享cookie
- asp.net – Infragistics WebGrid与Telerik网格
- 在ASP.NET MVC中搜索路径
- asp.net-mvc-4 – 在ASP.Net MVC 4和Autofac中注
- asp.net-web-api – SelfHosted AspNet WebAPI与
- asp.net – 在web-farm网站上将machineKey添加到
- asp.net-mvc – ASP.NET MVC Web API缓存控制头部
- asp.net-mvc – Web API的压缩过滤器
- 如何在ASP.NET和C#中加载下拉列表?
- 为什么NuPack生成的NinjectMVC3.cs无法编译? (或
- asp.net-mvc – 大型Web应用程序中的Windows Wor
- asp.net-mvc – 安装KB2993928后,ASP.NET MVC4解
