从依赖注入容器.NET CORE中读取请求标头

发布于 2025-02-07 16:14:23 字数 1685 浏览 3 评论 0原文

我有一些疑问,要使用.NET Core从DI容器访问HTTPContext(我使用的.NET 6是特定的)。我的目的是获取请求标题,例如相关性。这是我的DI容器代码。

        services.AddControllers()
                .ConfigureApiBehaviorOptions(o =>
                {
                    o.InvalidModelStateResponseFactory = c =>
                    {
                        var keys = c.ModelState.Where(l => l.Value.Errors.Count > 0).Select(k => k.Key).ToList();
                        string error = string.Empty;

                        if (keys != null)
                        {
                            error = keys.Count <= 1 ? keys[0] : keys[1];
                            error = error.Replace("$.", string.Empty);
                        }

                        error = $"Field: {error}. Message: {c.ModelState.Values.ElementAt(0).Errors[0].ErrorMessage}";
                        
                        //GET REQUEST HEADER
                        //string correlationId = retrieve correlationId from request header
                        Response response = new();
                        response.Fail(correlatinId, error);

                        return new BadRequestObjectResult(response);
                    };
                })
                .AddFluentValidation(o =>
                {
                    o.ImplicitlyValidateChildProperties = true;
                    o.ImplicitlyValidateRootCollectionElements = true;
                    o.RegisterValidatorsFromAssemblyContaining<LogErrorValidation>();
                });

我的代码段的目的是用自定义响应模型覆盖不良请求响应模型,因为我正在使用流利的验证。我的自定义响应模型由 coloreLationId(guid)消息(字符串)组成。

是否可以从DI容器中检索请求标头?

谢谢。

I've got some question about accessing HttpContext from DI Container for .NET Core (I am using .NET 6 to be specific). My purpose is to get request header e.g. CorrelationId. Here is my DI Container code.

        services.AddControllers()
                .ConfigureApiBehaviorOptions(o =>
                {
                    o.InvalidModelStateResponseFactory = c =>
                    {
                        var keys = c.ModelState.Where(l => l.Value.Errors.Count > 0).Select(k => k.Key).ToList();
                        string error = string.Empty;

                        if (keys != null)
                        {
                            error = keys.Count <= 1 ? keys[0] : keys[1];
                            error = error.Replace("$.", string.Empty);
                        }

                        error = 
quot;Field: {error}. Message: {c.ModelState.Values.ElementAt(0).Errors[0].ErrorMessage}";
                        
                        //GET REQUEST HEADER
                        //string correlationId = retrieve correlationId from request header
                        Response response = new();
                        response.Fail(correlatinId, error);

                        return new BadRequestObjectResult(response);
                    };
                })
                .AddFluentValidation(o =>
                {
                    o.ImplicitlyValidateChildProperties = true;
                    o.ImplicitlyValidateRootCollectionElements = true;
                    o.RegisterValidatorsFromAssemblyContaining<LogErrorValidation>();
                });

The purpose of my code snippet is to override Bad Request response model with custom response model since I am using Fluent Validation. My custom response model consist of correlationId (GUID) and message (string).

Is it possible to retrieve request header from DI container?

Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月棠 2025-02-14 16:14:23

Welp,我想我想念一些东西,可以做到

services.AddControllers()
                .ConfigureApiBehaviorOptions(o =>
                {
                    o.InvalidModelStateResponseFactory = c =>
                    {
                        var keys = c.ModelState.Where(l => l.Value.Errors.Count > 0).Select(k => k.Key).ToList();
                        string error = string.Empty;

                        if (keys != null)
                        {
                            error = keys.Count <= 1 ? keys[0] : keys[1];
                            error = error.Replace("$.", string.Empty);
                        }
                        //Read HTTP Context from Action Context (in this case is c)
                        var correlationId = c.HttpContext?.Request?.Headers?["CorrelationId"].FirstOrDefault();
                        error = $"Field: {error}. Message: {c.ModelState.Values.ElementAt(0).Errors[0].ErrorMessage}";

                        Response response = new();
                        response.Fail(correlationId, error);

                        return new BadRequestObjectResult(response);
                    };
                })
                .AddFluentValidation(o =>
                {
                    o.ImplicitlyValidateChildProperties = true;
                    o.ImplicitlyValidateRootCollectionElements = true;
                    o.RegisterValidatorsFromAssemblyContaining<LogErrorValidation>();
                });

Welp, I guess I miss something, it can be done with

services.AddControllers()
                .ConfigureApiBehaviorOptions(o =>
                {
                    o.InvalidModelStateResponseFactory = c =>
                    {
                        var keys = c.ModelState.Where(l => l.Value.Errors.Count > 0).Select(k => k.Key).ToList();
                        string error = string.Empty;

                        if (keys != null)
                        {
                            error = keys.Count <= 1 ? keys[0] : keys[1];
                            error = error.Replace("$.", string.Empty);
                        }
                        //Read HTTP Context from Action Context (in this case is c)
                        var correlationId = c.HttpContext?.Request?.Headers?["CorrelationId"].FirstOrDefault();
                        error = 
quot;Field: {error}. Message: {c.ModelState.Values.ElementAt(0).Errors[0].ErrorMessage}";

                        Response response = new();
                        response.Fail(correlationId, error);

                        return new BadRequestObjectResult(response);
                    };
                })
                .AddFluentValidation(o =>
                {
                    o.ImplicitlyValidateChildProperties = true;
                    o.ImplicitlyValidateRootCollectionElements = true;
                    o.RegisterValidatorsFromAssemblyContaining<LogErrorValidation>();
                });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文