0

problem

How to get response body on invoke next context using custom middle ware ??

After reach to line of await _next.Invoke(context) from debug;

not return json data from action result getusermenu

[HttpGet(Contracts.ApiRoutes.Security.GetUserMenus)]
 public IActionResult GetUserMenu(string userId)
        {
            string strUserMenus = _SecurityService.GetUserMenus(userId);
            return Ok(strUserMenus);
        }

I need to get response body from action result above

header :
key : Authorization
value : ehhhheeedff .

my code i try it :

public async Task InvokeAsync(HttpContext context, DataContext dataContext)
        {


            // than you logic to validate token              

            if (!validKey)
            {
                context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                await context.Response.WriteAsync("Invalid Token");
            }
            //if valid than next middleware Invoke
            else
            {
                await _next.Invoke(context);
// i need after that get result on last of thread meaning return data of usermenu

            }
        }
    }
 public static class TokenExtensions
    {
        public static IApplicationBuilder UseTokenAuth(this IApplicationBuilder builder)
        {
              return builder.UseMiddleware<TokenValidateMiddleware>();

        }
    }


          [no return data from access token][1]

https://i.stack.imgur.com/PHUMs.png

if(validtoken)
{
continue display getusermenuaction and show result

}

when valid token it return data like below on browser googlechrom

[
  {
    "form_name": "FrmAddPrograms",
    "title": "Adding Screens",
    "url": "",
    "permissions": {
      "Insert": "True",
      "Edit": "True",
      "Read": "True",
      "Delete": "True",
      "Print": "True",
      "Excel": "False",
      "RecordList": "False"
    }
  },

but on my app browser return not valid token

  • What kind of response are you expecting? Calling next on the request delegate just forwards the request to the next middleware in line or the request reaches a backstop handler provided by ASP.NET Core when it creates the pipeline, which sends the request back along the pipeline in the other direction. – Dennis VW Sep 15 '19 at 08:43
  • forword request to nextmiddleware line and show response body – ahmed abed elaziz Sep 16 '19 at 05:06

1 Answers1

0

Try to get response body in custom middleware using below code:

public class CustomMiddleware
{
    private readonly RequestDelegate next;

    public CustomMiddleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task Invoke(HttpContext context)
    {

        if (!validKey)
        {
            context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
            await context.Response.WriteAsync("Invalid Token");
        }
        //if valid than next middleware Invoke
        else
        {
            Stream originalBody = context.Response.Body;

            try
            {
                using (var memStream = new MemoryStream())
                {
                    context.Response.Body = memStream;

                    await next(context);

                    memStream.Position = 0;
                    string responseBody = new StreamReader(memStream).ReadToEnd();//get response body here after next.Invoke()

                    memStream.Position = 0;
                    await memStream.CopyToAsync(originalBody);
                }

            }
            finally
            {
                context.Response.Body = originalBody;
            }
        }          
    }
}
Ryan
  • 19,118
  • 10
  • 37
  • 53
  • thank you for reply still return invalid token on browser although from debug it reach to isvalid =true and and from debug get value of string responseBody as i need and on postman show result correct but in browser show invalid token message this message i write on code on line of invalid token but why this message shown although code not hit invalid token – ahmed abed elaziz Sep 16 '19 at 07:47
  • @ahmed abed elaziz Do you mean the token is valid and the code `await context.Response.WriteAsync("Invalid Token");` never be hit when you add break points,but the browser output the error message?The token needs to start with `Bearer xxxxx`.Do you add `app.UseTokenAuth` just before `app.UseMvc`?Based on your code without token It works well,I think it is related to your token validation issure. – Ryan Sep 16 '19 at 08:12
  • on configure on startup.cs class i do app.UseMiddleware(); app.UseHttpsRedirection(); app.UseAuthentication(); app.UseCors("CorsData"); app.UseMvc(); but according to Bearer i dont start because id ont know can you tell me how – ahmed abed elaziz Sep 16 '19 at 08:19
  • i already use app.class of middleware have app.tokenauth before app.usemvc but bearer cannot know any thing about that can you tell me how to start with bearer – ahmed abed elaziz Sep 16 '19 at 08:25
  • @ahmed abed elaziz Oh,forget that if you works well using postman by the same token...But JWT authentication itself will authenticate the token and return the result,there's no need to write a custom middleware.Again, it seems not related to your question title.You could ask a new thread and post necessary code. – Ryan Sep 16 '19 at 08:55
  • can you clear more your answer mean start with bearer or not this is what i need only – ahmed abed elaziz Sep 16 '19 at 09:14
  • @ahmed abed elaziz No,If you do not use Bearer token, then you do not need to.https://stackoverflow.com/questions/40375508/whats-the-difference-between-jwts-and-bearer-token – Ryan Sep 17 '19 at 01:34
  • thank you for reply result of your code above show success on postman but not show on my browser why . my browser used is google chrome browser – ahmed abed elaziz Sep 19 '19 at 03:52
  • @ahmed abed elaziz how do you send request in your browser?Does it have a valid token and come into the `if (!validKey)`? – Ryan Sep 19 '19 at 05:32