C# 使用 .net 会员服务提供商进行程序化登录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/243851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
programmatic login with .net membership provider
提问by ddc0660
I'm trying to unit test a piece of code that needs a currently logged in user in the test. Using the .Net 2.0 Membership Provider, how can I programmatically log in as a user for this test?
我正在尝试对需要当前登录用户的一段代码进行单元测试。使用 .Net 2.0 Membership Provider,我如何以编程方式以用户身份登录此测试?
回答by Craig Stuntz
Does your code actually need a user logged in via ASP.NET, or does it just need a CurrentPrincipal? I don't think you need to programmatically log in to your site. You can create a GenericPrincipal, set the properties you need, and attach it to, for example Thread.CurrentPrincipal or a mocked HttpContext. If your code actually needs RolePrincipal or something then I would change the code to be less coupled to ASP.NET membership.
您的代码是否真的需要用户通过 ASP.NET 登录,还是只需要 CurrentPrincipal?我认为您不需要以编程方式登录到您的网站。您可以创建一个GenericPrincipal,设置您需要的属性,并将其附加到,例如 Thread.CurrentPrincipal 或模拟的 HttpContext。如果您的代码实际上需要 RolePrincipal 或其他东西,那么我会更改代码以减少与 ASP.NET 成员资格的耦合。
回答by Rune Grimstad
Using your Membership Provider you can validate a user using Membership.ValidateUser. Then you can set the authentication cookie using FormsAuthentication.SetAuthCookie. As long as you have a cookie container this should allow you to log in a user.
使用您的 Membership Provider,您可以使用 Membership.ValidateUser 验证用户。然后您可以使用 FormsAuthentication.SetAuthCookie 设置身份验证 cookie。只要您有一个 cookie 容器,这应该允许您登录用户。
回答by user31934
I've found it most convenient to create a disposable class that handles setting and resetting Thread.CurrentPrincipal.
我发现创建一个处理设置和重置 Thread.CurrentPrincipal 的一次性类最方便。
public class TemporaryPrincipal : IDisposable {
private readonly IPrincipal _cache;
public TemporaryPrincipal(IPrincipal tempPrincipal) {
_cache = Thread.CurrentPrincipal;
Thread.CurrentPrincipal = tempPrincipal;
}
public void Dispose() {
Thread.CurrentPrincipal = _cache;
}
}
In the test method you just wrap your call with a using statement like this:
在测试方法中,您只需使用如下所示的 using 语句包装您的调用:
using (new TemporaryPrincipal(new AnonymousUserPrincipal())) {
ClassUnderTest.MethodUnderTest();
}
回答by user31934
if(Membership.ValidateUser("user1",P@ssw0rd))
{
FormsAuthentication.SetAuthCookie("user1",true);
}