Ocelot: Is there any way to catch the 401?

Created on 16 Feb 2018  路  6Comments  路  Source: ThreeMammals/Ocelot

Hello, I have a question, I am validating the redirect based on a token and everything works fine, however I would like if I receive a 401 as a response, then another action is executed, in my case i want to register that failed attempt in database, is there any way to do this?... thanks in advance

question

All 6 comments

@FerAguilarR93

There are a few ways you can do this...

The easiest would be to have your own middleware registered before the Ocelot middlewares e.g.

builder.Configure(app => 
{
    app.Use401CatchingMiddleware();
    app.UseOcelot().Wait();
}

You would need to write the 401 catching middleware and that would need to look at the HttpResponse message status code and save to your database.

The other way to do it would be with a delegating handler you can see the docs for this here

Excuse me, I麓m trying this:

public async Task Invoke(HttpContext context)
        {
            await _next(context);
            if (context.Response.StatusCode > 400)
                Debug.WriteLine("An error has been ocurred");
            else
                Debug.WriteLine("All its ok");
        }

but StatusCode always is 200, I make a request to an url non existent and return 404 to browser but in my middleware always have 200 in statuscode, when when I disable Ocelot the status code is 404, the code that you put in your previous comment is on configure method right?
I麓m using .NET CORE 2 and I tried with this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            app.UseCatchingResponseMiddleware();
            app.UseOcelot().Wait();
        }

but I have the problem described above

@FerAguilarR93 I'll take a look!

@FerAguilarR93 please see https://github.com/TomPallister/Ocelot/pull/241

You need

 public async Task Invoke(HttpContext context)
        {
            await _next(context);

            context.Response.OnCompleted(state =>
            {
                var httpContext = (HttpContext)state;

                if (httpContext.Response.StatusCode > 400)
                    Debug.WriteLine("An error has been ocurred");
                else
                    Debug.WriteLine("All its ok");
                return Task.CompletedTask;
            }, context);
        }

My bad I forgot that the request doesnt start until the middleware pipeline has ended so you need to use this callback. You can actually put it wherever you want in the code, it doesnt have to be after _next.Invoke(context) but it doesnt really matter.

Hope this helps!

It's very useful, thank you for your help and your time, it's working now

@FerAguilarR93 good! No worries, happy to help :)

Was this page helpful?
0 / 5 - 0 ratings