小编blg*_*boy的帖子

Moq IServiceProvider/IServiceScope

我正在尝试创建一个模拟(使用Moq),IServiceProvider以便我可以测试我的存储库类:

public class ApiResourceRepository : IApiResourceRepository
{
    private readonly IServiceProvider _serviceProvider;

    public ApiResourceRepository(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
        _dbSettings = dbSettings;
    }

    public async Task<ApiResource> Get(int id)
    {
        ApiResource result;

        using (var serviceScope = _serviceProvider.
            GetRequiredService<IServiceScopeFactory>().CreateScope())
        {
            var context = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
            result = await
                context.ApiResources
                .Include(x => x.Scopes)
                .Include(x => x.UserClaims)
                .FirstOrDefaultAsync(x => x.Id == id);
        }

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

我创建Mock对象的尝试如下:

Mock<IServiceProvider> serviceProvider = new Mock<IServiceProvider>();

serviceProvider.Setup(x => x.GetRequiredService<ConfigurationDbContext>())
    .Returns(new ConfigurationDbContext(Options, StoreOptions));

Mock<IServiceScope> serviceScope = new Mock<IServiceScope>(); …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing moq .net-core asp.net-core

18
推荐指数
5
解决办法
7558
查看次数

单元测试.NET Standard 1.6库

我无法找到有关如何对.NET Standard 1.6类库(可以从.NET Core项目中引用)进行单元测试的最新文档.

这是project.json我的图书馆的样子:

{
  "supports": {},
  "dependencies": {
    "Microsoft.NETCore.Portable.Compatibility": "1.0.1",
    "NETStandard.Library": "1.6.0",
    "Portable.BouncyCastle": "1.8.1.2"
  },
  "frameworks": {
    "netstandard1.6": {}
  }
}
Run Code Online (Sandbox Code Playgroud)

现在剩下的任务是能够创建某种可以进行单元测试的项目.目标是使用xUnit,因为这似乎是.NET Core团队正在推动的.

我继续创建了另一个.NET可移植的库项目,它有一个如下所示的project.json:

{
  "supports": {},
  "dependencies": {
    "Microsoft.NETCore.Portable.Compatibility": "1.0.1",
    "NETStandard.Library": "1.6.0",
    "xunit": "2.2.0-beta4-build3444",
    "xunit.runner.visualstudio": "2.1.0"
  },
  "frameworks": {
    "netstandard1.6": {

    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我在该项目中的测试类如下所示:

using USB.EnterpriseAutomation.Security.DotNetCore;
using Xunit;

namespace Security.DotNetCore.Test
{
    public class AesEncryptionHelperTests
    {
        [Fact]
        public void AesEncryptDecrypt()
        {
            var input = "Hello world!";
            var encrypted = AesEncryptionHelper.AesEncrypt(input);
            var decrypted = AesEncryptionHelper.AesDecrypt(encrypted);

            Assert.Equal(input, …
Run Code Online (Sandbox Code Playgroud)

.net c# xunit.net .net-core project.json

16
推荐指数
2
解决办法
9630
查看次数

Elasticsearch:仅返回嵌套的inner_hits

我有以下查询:

GET /networkcollection/branch_routers/_search/
{
  "query": {
    "nested": {
      "path": "queries",
      "query": {
        "bool": {
          "must": [
            { "match": 
              { "queries.dateQuery": "20160101T200000.000Z" }
            }
          ]
        }
      },
      "inner_hits" : {}
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

这将返回"命中"对象(整个文档)以及"inner_hits"对象(嵌套在命中内).

有没有办法让我只返回出现在"inner_hits"结果中的匹配"查询"元素,而不是获取整个文档?

elasticsearch

14
推荐指数
1
解决办法
5239
查看次数

Angular 2 - angular-cli:在构建时设置全局变量

这是我第一次尝试部署Angular2应用程序.我想设置API端点的URL,我希望它在每个环境中都有所不同.

有没有办法制作ng版本或任何其他工具,允许在部署之前为我设置?

angular-cli angular

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

System.IdentityModel.Tokens.JwtSecurityToken自定义属性

我的AuthServer当前正在使用以下代码生成JwtSecurityToken:

var token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey);
var handler = new JwtSecurityTokenHandler();
var jwt = handler.WriteToken(token);
Run Code Online (Sandbox Code Playgroud)

有效负载如下所示:

{
  "unique_name": "myUserName",
  "sub": "myUserName",
  "role": "API_User",
  "iss": "Automation",
  "aud": "099153c2625149bc8ecb3e85e03f0022",
  "exp": 1486056731,
  "nbf": 1483464731
}
Run Code Online (Sandbox Code Playgroud)

我想在令牌有效负载中添加一些自定义字段/属性,例如ProfilePicURL,以便有效负载看起来像这样:

{
  "unique_name": "myUserName",
  "sub": "myUserName",
  "role": "API_User",
  "iss": "Automation",
  "aud": "099153c2625149bc8ecb3e85e03f0022",
  "exp": 1486056731,
  "nbf": 1483464731,
  "profilePicture": "http://url/user.jpg"
}
Run Code Online (Sandbox Code Playgroud)

如何添加这些自定义属性并确保令牌包含它们?

c# asp.net jwt

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

Angular2 rxjs - switchmap catch错误

我希望能够在调用时处理任何错误this.authService.refreshToken().可以在switchmap块中处理错误,或者在这种情况下如何处理错误?

post3(endpoint: string, body: string) : Observable<any> {
    if (this.authService.tokenRequiresRefresh()) {
      this.authService.tokenIsBeingRefreshed.next(true);
      return this.authService.refreshToken().switchMap(
        data => {
          this.authService.refreshTokenSuccessHandler(data);
          if (this.authService.loggedIn()) {
            this.authService.tokenIsBeingRefreshed.next(false);
            return this.postInternal(endpoint, body);
          } else {
            this.authService.tokenIsBeingRefreshed.next(false);
            this.router.navigate(['/sessiontimeout']);
            Observable.throw(data);
          }
        }
      );
    }
    else {
      return this.postInternal(endpoint, body);
    }
  }
Run Code Online (Sandbox Code Playgroud)

rxjs angular

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

ASP.NET Core DbContext注入

我有一个ConfigurationDbContext我想要使​​用的.它有多个参数,DbContextOptionsConfigurationStoreOptions.

如何将此DbContext添加到ASP.NET Core中的服务?

我在Startup.cs中尝试了以下内容:

ConfigureServices
....
services.AddDbContext<ConfigurationDbContext>(BuildDbContext(connString));
....


private ConfigurationDbContext BuildDbContext(string connString)
{
    var builder = new DbContextOptionsBuilder<ConfigurationDbContext>();
    builder.UseSqlServer(connString);

    var options = builder.Options;

    return new ConfigurationDbContext(options, new ConfigurationStoreOptions());
}
Run Code Online (Sandbox Code Playgroud)

c# entity-framework dependency-injection entity-framework-core asp.net-core

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

ASP.NET Core运行两个TestServer进行集成测试

我正在尝试为令牌管理API运行一些集成测试.API还要求令牌颁发者API正在运行.

总之,我的集成测试需要同时运行IdentityServer4 Web/API和Management API.当我创建两个实例时TestServer,似乎它们最终都是相同的BaseAddress(http://localhost).

private readonly TestServer _identityTestServer;
private readonly TestServer _mgmtTestServer;
private readonly AppMgmtConfig _config;
private readonly AdminClient _adminClient;
private const string _certificatePassword = "test";

public AdminClientTests() : base(nameof(AdminClientTests))
{
    var connectionString = GetConnectionString();
    var dbSettings = new DbSettings(connectionString);

    Environment.SetEnvironmentVariable("IdentityServer4ConnString",
        dbSettings.IdentityServerConnectionString);
    Environment.SetEnvironmentVariable("CertificatePassword", _certificatePassword);

    _identityTestServer = new TestServer(new WebHostBuilder()
        .UseStartup<USBIdentityServer.Startup>()
        .UseEnvironment("IntegrationTest"));
    USBIdentityServer.Program.InitializeDatabase(_identityTestServer.Host);

    _mgmtTestServer = new TestServer(new WebHostBuilder()
        .UseStartup<IdentityServer4.Management.Startup>()
        .UseEnvironment("IntegrationTest"));

    _config = GetConfig();
    _adminClient = new AdminClient(_config);
}
Run Code Online (Sandbox Code Playgroud)

注意: 我已经尝试过的事情:

  • 添加.UseUrls("http://localhost:5001")以查看TestServer是否将在该端口上运行.
  • 添加serverName.BaseAddress …

c# integration-testing asp.net-core

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

ASP.NET 核心路由不起作用

路由器是这样配置的:

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "api",
        template: "api/{action}/{id?}");
});

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "spa-fallback",
        template: "{*url}",
        defaults: new { controller = "Home", action = "Index"});
});
Run Code Online (Sandbox Code Playgroud)

我尝试请求的控制器操作如下所示:// GET api/values/5

[HttpGet("{id}")]
public string Get(int id)
{
    return "value" + id;
}
Run Code Online (Sandbox Code Playgroud)

当我请求http://localhost:54057/api/values/get 时,我得到“value0”。

当我请求http://localhost:54057/api/values/get 时,我得到“value0”。

当我请求http://localhost:54057/api/values/get/5 时,我得到一个 404 Not Found。

我的路由配置是否不正确,或者为什么“id”参数没有从 URL 传递到控制器操作?

asp.net asp.net-core-mvc

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

解密包含私钥的受密码保护的PEM

我有以下使用Bouncy Castle for C#创建加密私钥的方法:

public string GetPrivateKey(AsymmetricCipherKeyPair keyPair, string password)
{
    var generator = new Pkcs8Generator(keyPair.Private, Pkcs8Generator.PbeSha1_3DES);
    generator.IterationCount = 4;
    generator.Password = password.ToCharArray();
    var pem = generator.Generate();

    TextWriter textWriter = new StringWriter();
    PemWriter pemWriter = new PemWriter(textWriter);
    pemWriter.WriteObject(pem);
    pemWriter.Writer.Flush();
    string privateKey = textWriter.ToString();
    return privateKey;
}
Run Code Online (Sandbox Code Playgroud)

看起来像这样:

-----BEGIN ENCRYPTED PRIVATE KEY-----
...
-----END ENCRYPTED PRIVATE KEY-----
Run Code Online (Sandbox Code Playgroud)

我不知道如何在Decrypt方法中使用用于加密私钥的密码。现在,在不知道如何使用he来“解密”我的私钥password的情况下,我得到了以下异常:

Org.BouncyCastle.OpenSsl.PemException:创建ENCRYPTED私钥时出现问题:System.NullReferenceException:对象引用未设置为对象的实例。在Org.BouncyCastle.OpenSsl.PemReader.ReadPrivateKey(PemObject pemObject)

这是Decrypt方法的代码:

public string Decrypt(string base64Input, string privateKey, string password)
{
    var bytesToDecrypt = Convert.FromBase64String(base64Input);

    //get a stream from the …
Run Code Online (Sandbox Code Playgroud)

c# encryption bouncycastle pem private-key

6
推荐指数
1
解决办法
3152
查看次数