小编Rik*_*ard的帖子

无法从apicontroller中的OwinContext获取UserManager

我正在关注Microsoft示例以使用Identity 2.0.0实现电子邮件验证

我被困在这一部分

public ApplicationUserManager UserManager
{
   get
   {
      return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
   }
   private set
   {
      _userManager = value;
   }
}
Run Code Online (Sandbox Code Playgroud)

这适用于controllerHttpContext不包含ApiController中的任何GetOwinContext方法.

所以我试过HttpContext.Current.GetOwinContext()但方法GetUserManager不存在.

我无法找到一种方法来获得UserManager我在Startup.Auth.cs中的构建

// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
    //Configure the db context, user manager and role manager to use a single instance per request
    app.CreatePerOwinContext(ApplicationDbContext.Create);
    app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); 
    ...
}
Run Code Online (Sandbox Code Playgroud)

这条线

app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
Run Code Online (Sandbox Code Playgroud)

调用以下函数来配置 UserManager …

c# asp.net-web-api owin asp.net-identity

68
推荐指数
3
解决办法
7万
查看次数

使用Autofac将依赖项注入自定义Web API操作过滤器属性

我正在尝试解决我的自定义依赖项AuthorizeAttribute,我用它来装饰MVC4应用程序中的API控制器.问题是我不断获得NullReferenceException我在自定义过滤器中使用的服务依赖项.这是我的Autofac配置:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var builder = new ContainerBuilder();
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
        builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerApiRequest();
        builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>().InstancePerApiRequest();
        builder.RegisterAssemblyTypes(typeof(UserProfileRepository).Assembly)
            .Where(t => t.Name.EndsWith("Repository"))
            .AsImplementedInterfaces().InstancePerApiRequest();

        builder.RegisterAssemblyTypes(typeof(IUserProfileMapper).Assembly)
            .Where(t => t.Name.EndsWith("Mapper"))
            .AsImplementedInterfaces().InstancePerApiRequest();

        builder.RegisterAssemblyTypes(typeof(UserProfileSvc).Assembly)
            .Where(t => t.Name.EndsWith("Svc"))
            .AsImplementedInterfaces().InstancePerApiRequest();

        builder.RegisterWebApiFilterProvider(config);
        var container = builder.Build();
        var resolver = new AutofacWebApiDependencyResolver(container);
        config.DependencyResolver = resolver;
    }
}
Run Code Online (Sandbox Code Playgroud)

和我的自定义授权过滤器:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    public IAuthenticationSvc _authenticationSvc;
    protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        if (!base.IsAuthorized(actionContext))
        {
            return false;
        }
        var trueUserId = WebSecurity.CurrentUserId; …
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc dependency-injection autofac action-filter asp.net-web-api

19
推荐指数
3
解决办法
2万
查看次数

单元测试从抽象类继承的类

我的问题是我想在我的抽象类中存根一个属性,因为我在测试中的类使用了该属性.我目前正在使用最新版本的Moq.

我的抽象类看起来像这样:

public abstract class BaseService
{
    protected IDrawingSystemUow Uow { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我的测试课看起来像这样:

public class UserService : BaseService, IUserService
{
    public bool UserExists(Model model)
    {
        var user = this.Uow.Users.Find(model.Id);
        if(user == null) { return false; }

        reurn true;
    }
}
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚我怎么能破坏Uow财产.有人有任何线索吗?或者我的设计是不是很糟糕,我需要Uow在测试中转移到我的班级财产?

c# abstract-class unit-testing moq

7
推荐指数
1
解决办法
2138
查看次数

在Asp.net-Identity中使OAuth令牌无效

我想在Asp.net-Identity中使承载令牌无效.我试图调用UpdateSecurityStampAsync(userId),我可以看到我的用户的安全标记得到更新.但旧的代币仍然有效.这只会使cookie身份验证无效吗?

是否有可能以另一种方式解决它?

c# owin asp.net-identity asp.net-identity-2

5
推荐指数
2
解决办法
1613
查看次数

使用ClientId和ClientSecret进行Web API授权

我在我的web api授权中使用OWIN/Katana中间件.

流动.

我发布acess_tokenrefresh_token请求的客户端.

access_token有短暂的寿命,而refresh_token早已到期.

像往常一样,如果access_token到期,它将使用refresh_token请求另一个access_token.

现在,我的问题.由于我的refresh_token有很长的生命周期,看起来它失败了短命的access_token的目的.让我们说如果refresh_token被泄露,黑客仍然可以得到access_token,对吧?

我查看了谷歌和微软的OAuth实现,看起来他们还有这个额外的参数,你需要提供除了refresh_token.这就是client_idclient_secret.看起来它们是在API的开发者页面上登录时生成的.

现在,我如何在我的项目中实现它?我想要覆盖令牌创建并使令牌哈希基于ClientIdClientSecret.

我正在使用最新的web api的基本OWIN/Katana身份验证,我不打算使用像Thinktecture这样的其他授权服务器.我只想使用ASP.NET Web API 2默认提供的基本功能

Startup.OAuth.cs

public partial class Startup
{
   static Startup()
   {
      PublicClientId = "self";
      UserManagerFactory = () => new UserManager<IdentityUser>(new AppUserStore());
      var tokenExpiry = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["ApiTokenExpiry"]);

      OAuthOptions = new OAuthAuthorizationServerOptions
      {
          TokenEndpointPath = new PathString("/Token"),
          Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
          AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
          AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(tokenExpiry),
          AllowInsecureHttp = true,
          RefreshTokenProvider …
Run Code Online (Sandbox Code Playgroud)

asp.net asp.net-web-api owin katana asp.net-mvc-5

5
推荐指数
1
解决办法
8396
查看次数

强制EF ApplicationUser加载导航属性

我正在使用EF6/.Net 4.5.1在webform上的usercontrol中检索列表视图的数据.我已经修改了ApplicationUser以使用FK属性包含导航属性[1:1],该属性一直很好用.

public class ApplicationUser : IdentityUser
{
    public ApplicationUser()
    {
        CreateDate = DateTime.Now;
        :\\ deleted stuff
    }

    public int TaxID { get; set; }
    public System.Guid ApplicationId { get; set; }
    :\\ deleted stuff

    [ForeignKey("TaxID")]
    public virtual Personnel Personnel { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

该模型已迁移并进行了存储和检索测试.

完整的回发一切正常.

但是我在网页上添加了一个按钮,用于打开和关闭一个div,该div包含一个负责创建新成员的UserControl.UserControl抛出容器使用的事件.然后Container关闭包含UC的div,用Listview重新打开div,调用调用GetAllUsers()的Listview DataBind().

代码:

public IQueryable<ApplicationUser> GetAllUsers()
{
    var manager = HttpContext.Current.GetOwinContext()
                             .GetUserManager<ApplicationUserManager>();
    var users = manager.Users.OrderBy(c => c.TaxID);

    return users;
}
Run Code Online (Sandbox Code Playgroud)

UserControl将控件返回到Container后出现问题.

第一个检索 - 总是有一个ApplicationUser,它没有加载Navigation属性.这意味着列表视图中永远不会填充某些字段.

但是,后续检索(刷新页面或调用行的编辑)似乎会触发导航属性.

显示第一和第二检索的图象

  1. 如何强制EF包含导航属性.语法管理器.Users.Include()在此上下文中不存在.

  2. 只有列为ApplicationUser的动态代理的实体似乎才具有导航属性.所以我很困惑为什么初始检索永远不是dynamicproxy.

  3. listview的Datapager需要IQueryable来实现其分页.我没有调用.ToList(),因为Datapager知道什么时候这个工作得很好...一旦有一个完整的页面刷新.为什么导航属性需要刷新页面才能实现?

任何帮助......在此先感谢...

c# asp.net entity-framework webforms asp.net-identity

5
推荐指数
1
解决办法
1063
查看次数

模拟IIndex &lt;TKey,TValue&gt;

我将IIndex作为工厂来决定要使用的服务。当我尝试对CommunicationJob类进行单元测试时,我在尝试使用IIndex模拟。

public class CommunicationJob : BaseJob
{
    private readonly IRepo<Notification> _nr;
    private readonly IIndex<string, IService> _cs;

    public CommunicationJob
    (
        IRepo<Notification> nr,
        IIndex<string, IService> cs
    )
    {
        _nr= nr;
        _cs= cs;
    }

    public void Do(DateTime date)
    {
        foreach (var n in _nr.GetList())
        {
            _cs[n.GetType().Name].Send(n);

            nr.Sent = DateTime.Now;
            nr.Update(n, true);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是这是_cs [n.GetType()。Name]为空。有谁能解决我的问题吗?一种解决方案是在测试之前启动Autofac,但是我不知道如何在测试上下文中加载AutoFac。

我的测试如下所示:

[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
public void WithNotifications(int numberOfNotifications)
{
    var fixture = new TestCommunicationJobFixture();

    var sut = fixture.WithNotifications(numberOfNotifications).GetSut();
    sut.Do(new DateTime());

    fixture.MockCommunicationService.Verify(x => x["EmailNotification"].Send(It.Is<Notification>(z => z.Sent …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing moq autofac

3
推荐指数
1
解决办法
1351
查看次数

模拟HttpResponeBase和HttpRequestBase时出现问题

我有一个mvc 3项目,我想模拟HttpResonseBase和HttpRequestBase.我使用RhinoMocks 3.6来模拟myobjects.我的测试代码右边看起来像这样.

[TestMethod]
public void Test()
{
    MockRepository repo = new MockRepositoy();
    HttpContextBase mockHttpContext= repo.StrictMock<HttpContextBase>();
    HttpRequestBase mockRequest = repo.StrictMock<HttpRequestBase>();
    HttpResponseBase mockResponse = repo.StrictMock<HttpResponseBase>();
    ICookie mockCookie = repo.StrictMock<ICookie>();
    Controller instanceToTest = new Controller(mockCookie);

    SetupResult.For(mockHttpContext.Request).Return(mockRequest);
    SetupResult.For(mockHttpContext.Response).Return(mockResponse);

    mocks.Replay(context);

    instanceToTest.ControllerContext = new ControllerContext(mockHttpContext, new RouteData(), instanceToTest);

    mockCookie.Expect(x=>x.MethodToExpect("Test",mockRequest,mockResponse);


    mockRepository.ReplayAll();
    instanceToTest.MethodToTest();
    mockRepository.VerifyAll();
}
Run Code Online (Sandbox Code Playgroud)

当我运行测试时,我得到了这个错误消息;

Rhino.Mocks.Exceptions.ExpectationViolationException: ICookie.MethodToExpect("Test", System.Web.HttpResponseBase, System.Web.HttpRequestBase); Expected #0, Actual #1.
ICookie.MethodToExpect("Test", HttpResponseBaseProxy); Expected #1, Actual #0.
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

c# unit-testing rhino-mocks asp.net-mvc-3

0
推荐指数
1
解决办法
1471
查看次数