【问题标题】:How to get response body using custom middle ware?如何使用自定义中间件获取响应正文?
【发布时间】:2020-01-16 05:26:04
【问题描述】:

问题

如何使用自定义中间件在调用下一个上下文时获取响应正文?

从调试到达 await _next.Invoke(context) 行后;

不从操作结果getusermenu返回json数据

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

我需要从上面的操作结果中获取响应正文

header :
key : Authorization
value : ehhhheeedff .

我的代码我试试看:

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

}

当令牌有效时,它会在浏览器 googlechrom 上返回如下数据

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

但在我的应用浏览器返回 无效的令牌

【问题讨论】:

  • 您期待什么样的回应?在请求委托上调用 next 只会将请求转发到队列中的下一个中间件,或者请求到达 ASP.NET Core 在创建管道时提供的支持处理程序,该处理程序将请求沿管道发送回另一个方向。跨度>
  • 转发请求到下一个中​​间件行并显示响应正文

标签: jwt asp.net-core-2.0 c#-7.0 jwt-auth


【解决方案1】:

尝试使用以下代码在自定义中间件中获取响应正文:

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;
            }
        }          
    }
}

【讨论】:

  • 感谢您的回复仍然在浏览器上返回无效令牌,尽管从调试它到达 isvalid =true 并且从调试获取字符串 responseBody 的值,因为我需要和邮递员显示结果正确但在浏览器中显示无效令牌消息此消息我写在无效令牌行的代码上,但为什么显示此消息虽然代码未命中无效令牌
  • @ahmed abed elaziz 你的意思是token有效并且添加断点时代码await context.Response.WriteAsync("Invalid Token");永远不会被命中,但是浏览器输出错误信息?token需要以@987654323开头@.你是在app.UseMvc之前加app.UseTokenAuth吗?根据你的代码没有令牌效果很好,我认为这与你的令牌验证问题有关。
  • 在 startup.cs 类上配置我做 app.UseMiddleware(); app.UseHttpsRedirection(); app.UseAuthentication(); app.UseCors("CorsData"); app.UseMvc();但根据 Bearer 的说法,我没有开始,因为我不知道你能告诉我怎么做
  • 我已经使用 app.class 的中间件在 app.usemvc 之前有 app.tokenauth 但是承载者对此一无所知,你能告诉我如何从承载者开始
  • @ahmed abed elaziz 哦,忘记了,如果你用同样的令牌使用邮递员工作得很好......但是 JWT 身份验证本身会验证令牌并返回结果,不需要编写自定义中间件.再次,它似乎与您的问题标题无关。您可以问一个新线程并发布必要的代码。
猜你喜欢
  • 2022-08-24
  • 2016-07-09
  • 2020-01-14
  • 1970-01-01
  • 1970-01-01
  • 2017-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多