Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

Endpoint is null when accessed in middleware during asp.net core 3.1 integration test

I run integration tests for my asp.net core application, the call passes from multiple middle-wares but stops at one of them which has the following line :

var endpoint = context.Features.Get<IEndpointFeature>()?.Endpoint;
var attribute = endpoint?.Metadata.GetMetadata<AllowAHeader>();

The endpoint is null.

public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup>
            where TStartup : class
        {
            protected override IHostBuilder CreateHostBuilder()
            {
                var builder = Host.CreateDefaultBuilder()
                                  .ConfigureWebHostDefaults(x =>
                                  {
                                      x.UseStartup<TStartup>().UseTestServer();
                                  });
                return builder;
            }
    
            protected override void ConfigureWebHost(IWebHostBuilder builder)
            {
                var configuration = new ConfigurationBuilder()
                    .AddJsonFile("appsettings.json")
                    .Build();

               builder.ConfigureTestServices(services =>
               {
                   services.RemoveAll<DbContext>();
                   services.RemoveAll<DbContextOptions>();

                   foreach (var option in services.Where(s => 
                   s.ServiceType.BaseType == 
                       typeof(DbContextOptions)).ToList())
                  {
                    services.Remove(option);
                  }

                  services.AddDbContext<DbContext>(options =>
                 {
                   options.UseInMemoryDatabase("Testing");
                 });
              });

            }
        }

Here is the test

public class ClientTests : IClassFixture<CustomWebApplicationFactory<TestStartup>>
    {
        private readonly HttpClient _client;

        public ClientTests(CustomWebApplicationFactory<TestStartup> customWebApplicationFactory)
        {
            _client = customWebApplicationFactory.CreateClient();
        }

        [Fact]
        public async Task GetClients()
        {
            _client.DefaultRequestHeaders.Add("X-Integration-Testing", "True");
            _client.DefaultRequestHeaders.Add("X-Integration-Authroize", "Basic");

            var result = await _client.PostAsync("v1/client", null);
        }
    }

The TestStartup :

public class TestStartup : Startup
    {
        public TestStartup(IConfiguration configuration)
            : base(configuration)
        {
        }

        protected override void ConfigureMiddlewareForIntegrationTest(IApplicationBuilder app)
        {
            app.UseMiddleware<AuthenticatedTestRequestMiddleware>();
        }
    }


 public class AuthenticatedTestRequestMiddleware
    {
        public const string TestingHeader = "X-Integration-Testing";
        public const string TestingHeaderAuthValueValue = "X-Integration-Authroize";

        private readonly RequestDelegate _next;

        public AuthenticatedTestRequestMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
        
            if (context.Request.Headers.Keys.Contains(TestingHeader))
            {
                 if (context.Request.Headers.Keys.Contains(TestingHeaderAuthValueValue))
                {
                    var encoded = "Basic " + System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes("user" + ":" + "123456"));
                    context.Request.Headers.Add("Authorization", encoded);
                }
            }
        
        }
        
    }
question from:https://stackoverflow.com/questions/66048606/endpoint-is-null-when-accessed-in-middleware-during-asp-net-core-3-1-integration

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...