.NET Core Middleware

      

Scenario:

MVC issue with 'The antiforgery token could not be decrypted' in web farm.

Solution:

Per MSDN:

Middleware is software that's assembled into an app pipeline to handle requests and responses. Each component:

  • Chooses whether to pass the request to the next component in the pipeline.
  • Can perform work before and after the next component in the pipeline.

Request delegates are used to build the request pipeline. The request delegates handle each HTTP request.

Request delegates are configured using Run, Map, Use extension methods.


1. HandleError

     
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Http;
    
    namespace MyCoreSolution
    {
        public class HandleError
        {
            private readonly RequestDelegate _next;
    
            public HandleError(RequestDelegate next)
            {
                _next = next;
            }
    
            public async Task Invoke(HttpContext context)
            {
                if (context.Request.Path.Value != null && (context.Request.Path.Value.Contains("Error")))
                {
                    await _next(context).ConfigureAwait(false);
    
                    switch (context.Response.StatusCode)
                    {
                        case 404:
                            HandlePageNotFound(context);
                            break;
                        default:
                            HandleException(context);
                            break;
                    }
                }
            }
    
            private static void HandleException(HttpContext context)
            {
                context.Response.Redirect("/UnknowError");
            }
    
            private static void HandlePageNotFound(HttpContext context)
            {
                context.Response.Redirect("/404");
            }
        }
    }

2. Startup.cs

     app.UseMiddleware<HandleError>();

No comments:

Post a Comment

Move Github Sub Repository back to main repo

 -- delete .gitmodules git rm --cached MyProject/Core git commit -m 'Remove myproject_core submodule' rm -rf MyProject/Core git remo...