Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpContext GetEndpoint on modified request path .net 5

I'm trying to create a middleware to handle country code in the url. The code i have works great for removing the country code, so it's routed to the correct endpoint in the mvc pipeline.

The problem i have is that i need to do some actions depending on if the endpoint has a certain attribute or not.

I see that HttpContext has a method GetEndpoint, and this is exactly what i need.

When the countryCode is in the url (mysite.com/us/home/Index), the GetEndpoint returns null.

But if i enter the site without the countryCode in the url (mysite.com/home/Index), then the GetEndpoint works.

How can i use the GetEndpoint() method on the modified request url?

Is it another property on HttpContext i need to change?

public async Task InvokeAsync(HttpContext httpContext)
{
    // mysite.com/us/home/Index
    var currentAddress = httpContext.Request.Path; 
    
    // mysite.com/home/Index
    httpContext.Request.Path = ExtractCountryCodeFromUrl(currentAddress); 

    var endpoint = httpContext.GetEndpoint(); // null

    var hasMyAttribute = endPoint.Metadata.GetMetadata<MyAttribute>();
    // Do something...

    await next(httpContext);
}
like image 554
Shomlings Avatar asked Jun 10 '26 00:06

Shomlings


1 Answers

I had the same problem, the solution for the problem (at least mine) was the order of middlewares in the Startup: your custom middleware must be after the UseRouting()

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseMiddleware<MyCustomMiddleware>();

    app.UseAuthorization();

    app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
like image 90
Lorenzo Avatar answered Jun 11 '26 13:06

Lorenzo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!