Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke method/Do action before every POST/GET request .NET Core

What I am trying to achieve - My application is simply ASP .Net Core application. It is not Web API. I want to execute method before every post/get request from my app to external sources, for example: I am sending a post request, to check SSL expiry date to some website API and it returns me a response. According to the response I am sending another request or not. I don't want to place call method statement before every request, I would like to do it globally.

I was trying to achieve this based on http://www.sulhome.com/blog/10/log-asp-net-core-request-and-response-using-middleware

As it occurs, this middleware works(I have it working) only for internal requests(routing requests inside application).

Is there any possibility to do it for all requests?

Thanks in advance

like image 394
Intern321 Avatar asked Mar 21 '17 13:03

Intern321


1 Answers

.NET Core allows to create custom middlewares to get into MV pipeline. Here is an example:

public class MyMiddleware
    {
        private readonly RequestDelegate _next;


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

        public async Task Invoke(HttpContext context)
        {
            //do your checkings
            await _next(context);
        }
}

In Startup.cs in Config method just regiester it:

app.UseMiddleware<MyMiddleware>(Options.Create(options));
like image 118
miechooy Avatar answered Nov 09 '22 04:11

miechooy