小编Dr *_*izo的帖子

Web API全局错误处理在响应中添加自定义标头

我想知道是否有可能在发生内部服务器错误时设置一些自定义标头值?我目前在做:

public class FooExceptionHandler : ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {
        // context.Result already contains my custom header values
        context.Result = new InternalServerErrorResult(context.Request);
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里,我还想设置一些标头值,但是虽然它出现在请求中,但响应不包含它.

有办法做到这一点吗?

c# http-headers asp.net-web-api exceptionhandler

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

SqlParameter 如何知道类型

我想SqlParameter知道未指定时如何知道类型?

例如,在实例化参数对象时,您不需要指定 DB 类型。以某种方式执行命令时,.net 会为您处理此问题。在幕后是否有某种转换正在发生?当你做/不明确指定类型时是否有成本?

.net ado.net sqlparameter

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

Azure Function 中毒队列警报

是否可以从位置队列创建警报?我有一个 blob 触发函数,但是当它失败x多次时,它会将此消息扔到有害队列中。我想做的是当该毒物队列的计数为 时创建警报x。

  1. 我可以使用 sidecart 方法来做到这一点,其中我有一个独立的服务来监视毒物队列
  2. 看到了这种方法/sf/answers/3243392911/
  3. 希望使用blobproperties覆盖来存储一些,metadata以便我可以跟踪故障,但似乎没有办法做到这一点?我正在考虑最后一次尝试跟踪一个事件来声明moving message to poison queue

有更好的方法吗?

        [FunctionName("MyFunction")]
        public async Task Run(
            [BlobTrigger("input-queue", Connection = "ConnectionString")] Stream blobContent,
            string name,
            System.Uri uri,
            IDictionary<string, string> metaData,
            BlobProperties properties,
            ILogger log)
Run Code Online (Sandbox Code Playgroud)

编辑 注意到函数的重载:

        [FunctionName("MyFunction")]
        public async Task Run(
            [BlobTrigger("input-queue", Connection = "ConnectionString")] ICloudBlob blobContent,
            string name,
            System.Uri uri,
            IDictionary<string, string> metaData,
            BlobProperties properties,
            ILogger log)
        {
            if (!blobContent.Metadata.ContainsKey("mycount"))
            {
                blobContent.Metadata["mycount"] = "1";
                await blobContent.SetMetadataAsync();
            } …
Run Code Online (Sandbox Code Playgroud)

poison-queue azure-functions

4
推荐指数
1
解决办法
1612
查看次数

使用Action <T>的表达式树可能吗?

我正在努力解决一些问题.我最初创建了一个通用层,它位于我的业务对象和工作正常的数据访问层之间.然后,我最近阅读了一些名为Expression Trees的内容,它显然更有效,并且已经证明是这样,因为我将Activator.CreateInstance()与表达式交换,并以指数方式改进了我的通用层.

我还在阅读有关整个区域(表达式)的一些内容,但我遇到了一些我想尝试制作通用的代码.目前,你必须传递一个具体的类型,如字符串,int,十进制等.我有点通用.我试了几件但失败了.我想要通用的位是Action,我不想传入一个字符串,我希望能够传递一般属性的类型,即typeof(T).GetProperty("Forename").PropertyType.这可能吗?正在考虑做一个有点foo bar的switch语句.

在此先感谢Onam.

public class TTT<T> where T : new()
{
    public void Do(object t)
    {
        MethodInfo info = typeof(T).GetProperty("Forename").GetSetMethod();

        ParameterExpression param = Expression.Parameter(typeof(string), "val");

        MethodCallExpression call = Expression.Call(Expression.Constant(t), info,
            new ParameterExpression[] { param });

        Action<string> action = Expression.Lambda<Action<string>>(call, param).Compile();

        action("hi");
    }
}
Run Code Online (Sandbox Code Playgroud)

c# generics reflection expression-trees

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

为个人/客户建模联系人详细信息

我想知道是否有一种更优雅的方式来管理个人的联系方式.暂时忘记SQL方面,我很想知道如何通过DDD方法尝试驱动它.

为了让DDD作为一个整体感到舒服,我正在愚弄一些代码并提出以下看起来很糟糕.

首先,我有一个名为Person的对象(为了这个帖子的目的而简化),我设想了添加和实质上管理不同的个人沟通方法的方法.

public class Person
{
    public Person()
    {
        this.ContactDetails = new List<ContactDetails>();
    }

    public void AssociateContactDetails(ContactDetails contactDetails)
    {
        var existingContactDetails = this.ContactDetails.FirstOrDefault(x => x.ContactType == contactDetails.ContactType);

        if (existingContactDetails != null)
        {
            this.ContactDetails.Remove(existingContactDetails);
        }

        this.ContactDetails.Add(contactDetails);
    }

    public IList<ContactDetails> ContactDetails { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)

我想到了两种方法.我有一个相当简单的对象,如下面的那个是非常通用的(使用松散的术语).

public enum ContactType
{
    Email, Telephone, Mobile, Post
}   

public class ContactDetails
{
    private readonly ContactType contactType;
    private readonly string value;

    public ContactDetails(ContactType contactType, string value)
    {
        this.contactType = contactType;
        this.value = value; …
Run Code Online (Sandbox Code Playgroud)

c# domain-driven-design software-design

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

NServiceBus Test.Initialize()给定键不存在

更新只是更详细地阅读Google群组,显然这是一个应用配置问题.尝试后会更新帖子.

我想知道在尝试单元测试NServiceBus时是否有人知道这个问题.

意识到我下面有两个初始化方法,但这是为了说明我想要做什么.根据请求堆栈跟踪.

(NServiceBus.LocalAddress)字典中不存在.(NServiceBus.LocalAddress)字典中不存在.

我相信堆栈跟踪的其他部分是一个抱怨InMemoryPersistence的红鲱鱼.然而,有一个谷歌小组也在谈论这个问题,他们遇到了同样的问题,这让我觉得它更像是一个NServiceBus问题,而不是编码错误.

Google群组链接https://groups.google.com/forum/m/#!topic/particularsoftware/424_6KCv6oI

应该提一下这些帖子.

https://github.com/Particular/NServiceBus.Testing/issues/20 https://github.com/Particular/NServiceBus.Testing/commit/f761c5391b03b05d967f2e368248c72522051d59

public static class CustomInit
    {
        public static void Init()
        {
            //Previous versions of NBUS, specifically 4.6.5
            //MessageConventionExtensions.IsEventTypeAction = MessageConfiguration.ForEvents();
            //MessageConventionExtensions.IsCommandTypeAction = MessageConfiguration.ForCommands();            

            //New 5.2.0 how to setup tests
            Test.Initialize(x => x.AssembliesToScan(GetAssembliesToScan()));

            Test.Initialize(
                x =>
                {
                    x.Conventions().DefiningCommandsAs([my namespace]);
                    x.Conventions().DefiningEventsAs([my namespace]);
                    x.AssembliesToScan(GetAssembliesToScan());
                });
        }

        private static IEnumerable<Assembly> GetAssembliesToScan()
        {
            return new[]
            {
                AssemblyFromType<ISomeInterface>()
            };
        }
}
Run Code Online (Sandbox Code Playgroud)

c# unit-testing nservicebus nservicebus5

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

Linq OrderBy子列表

我试图执行一个相当简单的顺序,但似乎正在努力如何去做.举个例子,我有这两个类.

public class Method
{
    public int Id { get; set; }

    public string Name { get; set; }

    public decimal Price { get; set; }

    public List<Slot> Slots { get; set; }
}

public class Slot
{
    public DateTime ExpectedDeliveryDate { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

使用下面的代码我想通过最便宜的选项订购,然后按最快的交货日期订购.

var methods = new List<Method>();

methods.Add(new Method { Id = 1, Name = "Standard", Price = 0M, Slots = new List<Slot> { new Slot { ExpectedDeliveryDate = DateTime.Now.AddDays(5).Date } } });
methods.Add(new Method …
Run Code Online (Sandbox Code Playgroud)

c# linq sorting

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

KeyVault 的 Kestrel Secure HTTPS X509 证书

我想使用存储在 KeyVault 中的 pfx 证书来保护我的 API,但是由于某种原因,这似乎不像我预期的那样工作。如果我的机器上安装了证书,它就可以完美运行。我想知道是否可以将证书存储在 KeyVault 中,然后以这种方式保护它,而不是在证书存储中查找它。

场景是我有一个与 KeyVault 对话的 .NET Core Web API。这个 KeyVault 包含我的 PFX 证书,当我上传时提示输入我的密码。所以在这一点上一切似乎都很好。

我有以下代码来检索和应用证书:

            var client = new KeyVaultClient(new KeyVaultCredential(GetToken));
            var cert = client.GetCertificateAsync("https://somekeyvaultsomewhere.vault.azure.net/", "my_tls_cert").Result;
            var certificate = new X509Certificate2(cert.Cer);

            var host = new WebHostBuilder()
                .UseKestrel(options =>
                {
                    const int PortNumber = 5001;
                    options.Listen(
                        new IPEndPoint(IPAddress.Any, PortNumber),
                        listenOptions =>
                        {
                            listenOptions.KestrelServerOptions.AddServerHeader = false;
                            listenOptions.UseHttps(certificate);
                        });
                })
                .CaptureStartupErrors(true)
                .UseStartup<Startup>()
                .Build();

            host.Run();
Run Code Online (Sandbox Code Playgroud)

我希望能够通过https端口访问我的 API5001。相反,我没有得到任何回应(无法访问网站)。

似乎一切都在运行,但不能击中任何东西。

在此处输入图片说明

这是可能的吗?

消耗的包裹:

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.6" /> …
Run Code Online (Sandbox Code Playgroud)

ssl x509certificate2 kestrel azure-keyvault asp.net-core

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

.NET Core 3.1 始终加密

使用 .NET Core 3.1 和 SQL Always Encrypted 时出现以下错误。3.1支持这个吗?也许我在这里遗漏了一些东西..

Keyword not supported: 'column encryption setting'.
Run Code Online (Sandbox Code Playgroud)

目前已安装以下软件包

    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.12.0" />
    <PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
    <PackageReference Include="Dapper" Version="2.0.30" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
    <PackageReference Include="Microsoft.Data.SqlClient.AlwaysEncrypted.AzureKeyVaultProvider" Version="1.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.AzureKeyVault" Version="3.1.1" />
    <PackageReference Include="Serilog.AspNetCore" Version="3.2.0" />
    <PackageReference Include="Serilog.Extensions.Logging" Version="3.0.1" />
    <PackageReference Include="Serilog.Settings.Configuration" Version="3.1.0" />
    <PackageReference Include="Serilog.Sinks.ApplicationInsights" Version="3.0.4" />
    <PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
Run Code Online (Sandbox Code Playgroud)

always-encrypted .net-core-3.1 asp.net-core-3.1

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

最少的 API 注册依赖项

我正在尝试注册依赖项,但奇怪的一件事是使用特定处理程序时。例如,采取一个简单的场景,例如:

using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
var handler = new CustomerHandler(); // Compiler error here

app.MapGet("/customers/{id}",
    (
        [FromQuery(Name = "msg")]string? name,
        [FromRoute(Name = "id")]string id) => handler.Get(id, name));
app.Run();
Run Code Online (Sandbox Code Playgroud)

处理程序在其构造函数中接受单个项目。

public class CustomerHandler
{
    private readonly IGetCustomerQuery _getCustomerQuery;

    public CustomerHandler(IGetCustomerQuery getCustomerQuery)
    {
        _getCustomerQuery = getCustomerQuery;
    }

    public async Task<IResult> Get(string id, string name)
    {
        return Results.Ok(new Customer { Id = id, Name = name });
    }
}
Run Code Online (Sandbox Code Playgroud)

我想指定这些依赖项的“正确”方法是什么?我通常会使用BuildServiceProvider()并使用Get<T>()来创建处理程序,但从我所读到的内容来看,这并不理想。所以我想理想的方法是创建这些实例吗?我应该放弃处理程序方法吗?

请注意,这是一个非常简单的示例,但示例的实现 IGetCustomerQuery将采用数据库的配置设置。我想使用传统的 …

c# .net-core asp.net-core minimal-apis

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