locked
Reject/Accept Method and Header RRS feed

  • Question

  • User718448626 posted

    I am at a lost as to how to reject or accept specific methods and header from asp.net core 2.2.  For example, I would only want post and get method with a custom header like "X-MYAPP-Version" 

    All the examples are related to CORS but none on non cross site access.   Thank you.

    Saturday, August 24, 2019 1:59 AM

Answers

  • User475983607 posted

    Build middleware to check the header.

        public class CustomVersionMiddleware
        {
            private readonly RequestDelegate _next;
    
            public CustomVersionMiddleware(RequestDelegate next)
            {
                _next = next;
            }
    
            public async Task Invoke(HttpContext context)
            {
                KeyValuePair<string, StringValues> header = context.Request.Headers.FirstOrDefault(x => x.Key == "X-MYAPP-Version");
    
                if(header.Key == null)
                {
                    // X-MYAPP-Version Header is missing 
                    // Do something
                }
                else
                {
                    string key = header.Key;
                    string value = header.Value;
                }
                
                await _next(context);
            }
        }
    
        public static class RequestCustomVersionMiddlewareExtensions
        {
            public static IApplicationBuilder UseCustomVersion(this IApplicationBuilder builder)
            {
                return builder.UseMiddleware<CustomVersionMiddleware>();
            }
        }
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                app.UseCustomVersion();

    https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/write?view=aspnetcore-2.2

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, August 24, 2019 12:37 PM