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);
}
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(); });
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With