0

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 = $"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.

1 Answer 1

0

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 = $"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>();
                });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.