小编tra*_*max的帖子

更改角色后刷新声明主要内容

我在改变dotnetcore身份中的角色时遇到了一些问题.

我有以下代码.

private async Task SetRoleToX(ClaimsPrincipal claimsPrincipal, string X)
{
    var currentUser = await UserManager.GetUserAsync(claimsPrincipal);
    var roles = await UserManager.GetRolesAsync(currentUser);

    await UserManager.RemoveFromRolesAsync(currentUser, roles);
    await UserManager.AddToRoleAsync(currentUser, X);
    await SignInManager.RefreshSignInAsync(currentUser);
}
Run Code Online (Sandbox Code Playgroud)

我无法更新ClaimsPrincipal.

我尝试过使用登录并注销.

如果我手动登录和退出,角色切换工作正常.

我一直在网上搜索,很多人说这应该工作:(

c# asp.net-identity .net-core asp.net-core-identity

11
推荐指数
1
解决办法
930
查看次数

在ASP.NET MVC3模型绑定器中使用依赖注入

我正在使用MVC3网站,试图使用Ninject来解决我的依赖关系.我有以下场景:

public class UserModelBinder : IModelBinder
{
    //[Inject]
    public UserDataService userData { get; set; }

    public object BindModel(
        ControllerContext controllerContext,
        ModelBindingContext bindingContext)
    {
        Guid UserID =
            (Guid)Membership.GetUser().ProviderUserKey;

        //userDataService = DependencyResolver.Current
        //    .GetService<UserDataService>();

        User user = userDataService.GetUser(UserID);

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

注意到注释的代码行?

我确实将活页夹注册Global.asax

ModelBinders.Binders[typeof(User)] = new UserModelBinder();
Run Code Online (Sandbox Code Playgroud)

所以我不能真正通过施工注射.

UserDataService有一连串的依赖:UserDataService -> UserRepository -> Context.所以在这里使用Ninject会很好.

问题是,当我取消注释[Inject]上面的userData声明,并尝试让Ninject注入对象作为参数时,它由于某种原因不起作用:我得到空引用异常.

(可能是UserDataService没有接口,我将对象绑定到自身:kernel.Bind<UserDataService>().ToSelf();??)

我在代码中有另一个注释行:

userDataService = DependencyResolver.Current
    .GetService<UserDataService>();
Run Code Online (Sandbox Code Playgroud)

如果取消注释,设置工作,我会插入正确的对象,但现在我们依赖DependencyResolver,这并不比说 userDataService = new UserDataService()

我错过了什么吗?是否有另一种方法将对象作为参数注入,而不是引入对Ninject或DependencyResolver的依赖?

.net c# asp.net-mvc dependency-injection ninject

10
推荐指数
2
解决办法
3604
查看次数

AutoMockContainer,支持具有非接口依赖性的automocking类

我有一个具有非接口依赖的构造函数:

public MainWindowViewModel(IWorkItemProvider workItemProvider, WeekNavigatorViewModel weekNavigator)
Run Code Online (Sandbox Code Playgroud)

我正在使用Moq.Contrib automockcontainer.如果我尝试自动锁定MainWindowViewModel类,由于WeekNavigatorViewModel依赖项,我收到错误.

是否有任何automocking容器支持非接口类型的模拟?

正如马克在下面所示; 是的你可以!:-)我将Moq.Contrib AutoMockContainer替换为Mark在他的答案中提出的东西,唯一的区别是自动生成的模拟被注册为单例,但你可以使这个可配置.这是最终的解决方案:

/// <summary>
/// Auto-mocking factory that can create an instance of the 
/// class under test and automatically inject mocks for all its dependencies.
/// </summary>
/// <remarks>
/// Mocks interface and class dependencies
/// </remarks>
public class AutoMockContainer
{
    readonly IContainer _container;

    public AutoMockContainer(MockFactory factory)
    {
        var builder = new ContainerBuilder();

        builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());
        builder.RegisterSource(new MoqRegistrationSource(factory));

        _container = builder.Build();
    }

    /// <summary>
    /// Gets or creates a mock …
Run Code Online (Sandbox Code Playgroud)

c# tdd moq mocking

9
推荐指数
1
解决办法
3454
查看次数

在使用 Polly 重试之前检查响应的字符串内容

我正在使用一个非常脆弱的 API。有时我500 Server ErrorTimeout,其他时间我还可以得到500 Server Error,因为我给它输入,它不能处理SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.

这两种情况都给了我,HttpRequestException但我可以查看来自服务器的回复消息并确定异常的原因。如果是超时错误,我应该再试一次。如果这是一个错误的输入,我应该重新抛出异常,因为再多的重试也无法解决错误数据的问题。

我想对 Polly 做的是在尝试重试之前检查响应消息。但是到目前为止我看到的所有样本都只包含异常类型。

到目前为止,我想出了这个:

        HttpResponseMessage response = null;
        String stringContent = null;
        Policy.Handle<FlakyApiException>()
             .WaitAndRetry(5, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
              async (exception, timeSpan, context) =>
            {
                response = await client.PostAsync(requestUri, new StringContent(serialisedParameters, Encoding.UTF8, "application/json"));
                stringContent = await response.Content.ReadAsStringAsync();

                if (response.StatusCode == HttpStatusCode.InternalServerError && stringContent.Contains("Timeout"))
                {
                    throw new FlakyApiException(stringContent);
                }
            });
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来进行这种检查?

c# retrypolicy polly

9
推荐指数
1
解决办法
5963
查看次数

尽管父作业已成功,但 Hangfire ContinueWithJob 仍处于等待状态

我通过ContinueJobWith<MyHandler>(parentJobId, x => x.DoWork()).

但是,第二个作业没有得到处理并且始终处于Awaiting状态: 父母成功,但工作未处理

工作本身是这样的: 卡在排队

为什么会发生这种情况以及在哪里检查结果?

  • 我们使用 Autofac 作为 DI 容器,但我们有自己的JobActivator实现,因为我们必须处理多租户。
  • 我们使用 SQL Server 2019 进行存储。
  • Hangfire 版本是 1.7.10
  • 这是 MVC 5 应用程序
  • 我在任何日志或调试过程中都没有看到任何错误/异常
  • 完成此操作后,我已将其添加到我们的 Autofac 注册中
            builder.RegisterType<BackgroundJobStateChanger>()
                   .As<IBackgroundJobStateChanger>()
                   .InstancePerLifetimeScope();
Run Code Online (Sandbox Code Playgroud)

这没有任何区别。

这是作业的执行方式:

var parentJobId = _backgroundJobClient.Schedule<Handler>(h => h.ConvertCertToTraining(certId, command.SetUpOneToOneRelationship), TimeSpan.FromSeconds(1));
var filesCopyJObId = _backgroundJobClient.ContinueJobWith<Handler>(parentJobId, h => h.CopyAttachedFiles());
_backgroundJobClient.ContinueJobWith<Handler>(filesCopyJObId, h => h.NotifyUser(command.CertificationToBeConvertedIds, _principal.GetEmail()));
Run Code Online (Sandbox Code Playgroud)

所有参数都是int,boolstring。如果我手动将等待的作业排入队列,它们将毫无问题地执行。

我添加了 Hangfire 日志记录,但在那里看不到任何问题:服务器启动、停止、作业更改状态,但在那里看不到任何明显错误。

我应该考虑哪些其他事情或者我应该在哪里/如何调试它?

c# hangfire

9
推荐指数
2
解决办法
536
查看次数

Azure Powershell抛出"未知用户类型"

我正在尝试针对AD帐户验证Powershell脚本(根据本指南):

$userName = "username@mydomain.com"
$securePassword = ConvertTo-SecureString -String "myPassword1" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($userName, $securePassword)
Add-AzureAccount -Credential $cred
Run Code Online (Sandbox Code Playgroud)

但是我收到错误:

Add-AzureAccount : unknown_user_type: Unknown User Type
At line:2 char:1
+ Add-AzureAccount -Credential $cred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Add-AzureAccount], AadAuthenticationFailedException
    + FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.Profile.AddAzureAccount
Run Code Online (Sandbox Code Playgroud)

我输入用户名/密码并不重要,即使是"adsfasdf",用户名和密码都会给我相同的结果.

以前有人修过这个问题吗?

powershell azure azure-powershell

8
推荐指数
1
解决办法
4999
查看次数

实体框架创建空迁移但坚持我的模型不同

今天是悲伤的一天.今天第一件事我看到EF异常说" 自创建数据库以来,支持'DomainContext'上下文的模型已经改变了. " 接近午夜,我仍然看到这个错误.这是我职业生涯的终结 - (

我很确定模型中没有任何变化,但错误出现了.我尝试过创建一个新的迁移,它是空的:

public void Up()
{
}
public void Down()
{
}
Run Code Online (Sandbox Code Playgroud)

应用此迁移没有任何好处 - 错误仍然存​​在.我使用了常见的建议将初始化设置为null:

Database.SetInitializer<DomainContext>(null);
Run Code Online (Sandbox Code Playgroud)

当我访问数据库时,它使错误消失了.但这让我非常困扰 - 每当我尝试通过代码运行迁移时,我再次看到类似的错误:

var configuration = new Migrations.Configuration();

configuration.TargetDatabase = new DbConnectionInfo("correct connection string", "System.Data.SqlClient");

var migrator = new DbMigrator(configuration);

migrator.Update(); // <<-- exception is thrown here
Run Code Online (Sandbox Code Playgroud)

Exception throw如下所示:System.Data.Entity.Migrations.Infrastructure.AutomaticMigrationsDisabledException:无法更新数据库以匹配当前模型,因为存在挂起的更改并且已禁用自动迁移.将挂起的模型更改写入基于代码的迁移或启用自动迁移.将DbMigrationsConfiguration.AutomaticMigrationsEnabled设置为true以启用自动迁移.

我已更新到EF 6.1(之前是6.0.2),但这没有任何区别.

困扰我的另一件事是我可以通过Nuget控制台运行迁移:

Update-Database
Run Code Online (Sandbox Code Playgroud)

运行良好,不会出现任何问题.但是,当我将DB初始化程序设置为自动运行迁移时:

var initializer = new MigrateDatabaseToLatestVersion<DomainContext, Migrations.Configuration>();
Database.SetInitializer(initializer);
var domainContext = new DomainContext();
domainContext.Database.Initialize(true); // <<-- this throws exception
Run Code Online (Sandbox Code Playgroud)

无法更新数据库以匹配当前模型,因为存在挂起的更改并且已禁用自动迁移.将挂起的模型更改写入基于代码的迁移或启用自动迁移.将DbMigrationsConfiguration.AutomaticMigrationsEnabled设置为true以启用自动迁移.

真正的问题是为什么EF在运行Nuget控制台和迁移DB-Initialiser时对模型有不同的哈希值?我怎样才能找出不同的东西(来自db-state的模型)?以及如何解决这个问题,所以我不必使用hacks(为db-initaliser分配null)?

c# ef-migrations entity-framework-6.1

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

使用Azure Active Directory - 一个应用程序在本地登录和发布时

我正在使用Azure Active Directory身份验证构建MVC应用程序.当我在本地开发时,我希望能够登录进行测试/开发.应用程序网址就像http://localhost:43400.这也被编码在AD应用Sign-On UrlReply Url.

当我将相同的应用程序部署到服务器时,应用程序URL已更改 - 变得类似myappname.azurewebsites.net,我无法使用相同的AD应用程序登录.我能管理的最好的办法就是通过登录过程,然后AD将我重定向回到localhost:43400错误状态.

有一些PostLogoutRedirectUri属性Startup.Auth.cs,我给应用程序,但它没有任何区别.

有没有使用相同Azure AD的本地应用程序和已部署应用程序的方法?

我可以使用不同的URL和密钥执行2个AD Applica,并web.config在部署中重写值.但这听起来不是最好的解决方案.还有什么我能做的吗?

UPD

这是我所指的位Startup.Auth.cs:

app.UseOpenIdConnectAuthentication(
    new OpenIdConnectAuthenticationOptions
    {
        ClientId = clientId,
        Authority = Authority,
        PostLogoutRedirectUri = postLogoutRedirectUri, // <-- this is coming from web.config, different in dev and prod

        Notifications = new OpenIdConnectAuthenticationNotifications()
        {
            .....

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

在此处查看完整代码.

在Azure AD应用程序中,我同时尝试将这两个地址作为回复URL: Azure AD应用程序回复URL

但AD只使用其中一个地址进行重定向,即使客户端指定了与其中一个记录匹配的重定向.

c# asp.net oauth azure azure-active-directory

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

Javascript奇怪的日期操作

我在一个看似有信誉的来源中遇到了一个奇怪的日期操作,我不明白.这是流行UI框架的支持文档中的示例的一部分:

var startDate = start.value();  // returns Date object
startDate = new Date(startDate);
startDate.setDate(startDate.getDate());
Run Code Online (Sandbox Code Playgroud)

现在逐行var startDate = start.value();返回Date对象并将其保存在startDate变量中.好在这里,没问题.

然后我们创建具有相同值的新Date对象并将其分配回同一个变量(稍微有些混乱,但我可以忍受它).

第三行是一个真正的谜题 - 我们得到月中的getDate某一天(通过)并将其指定为setDate同一个变量中的月份(通过).

现在的问题是:这是一个糟糕的代码,可能是未完成的重构遗留下来的吗?或者这是否真的有意义,它做了一些操作,如删除时间(看起来不像)?如果是,它会做什么?

UPD:代码示例在http://demos.telerik.com/kendo-ui/datepicker/rangeselection

javascript date

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

DocumentDB客户端生命周期

要访问DocumentDB/CosmosDB,我正在使用包Microsoft.Azure.DocumentDB.Core(v1.3.2).当我创建并初始化DocumentClient类时,我注意到了:

var documentClient = new DocumentClient(new Uri(endpointUrl), primaryKey);
await documentClient.OpenAsync();
Run Code Online (Sandbox Code Playgroud)

向端点发出了许多请求以获取有关索引和其他信息的信息.确切地说,有9个HTTP请求正在进行中.OpenAsync().这使得客户端的创建和激活在性能方面成本非常高 - 需要一秒钟才能将所有请求带回家.

因此,为了减轻这种代价高昂的操作,我正在制作DocumentClient一个单例,并在应用程序的生命周期内保持参考.

应用程序是Asp.Net Core MVC,这可能会将此对象的引用保留在内存中数天.

问题:可以将此对象保持为单例吗?如果不是,应该采取什么策略来处置它?或者有没有办法使初始化更便宜(即不要做出这些初始请求?).

c# azure lifetime-scoping azure-cosmosdb

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