zoukankan      html  css  js  c++  java
  • FilterContext/HttpContext 获取请求参数

    .Net Core 对于body多次读取,.net core2.0 使用EnableRewind(),.net core 3.0使用EnableBuffering(),该参数在第一次读取body之前开启,之后body信息可以多次读取;core时代取消了之前的stream.position=0写法,虽然var byts = new byte[request.ContentLength.Value]中的request.ContentLength.Value超过1024语法并没有错,但是对于流读取的话,一次最多是1024,如果一次需要读取的大于1024,也不会报错,会截断,就是读取的信息不全。这个是我在工作中对接ERP系统吸取的教训,搞了好久才发现内容被截断了,现在分享给大家,让你们少走点弯路。

    一、错误写法

    // 获取请求参数
    var request = actionContext.HttpContext.Request;
    request.EnableBuffering();
    var stream = actionContext.HttpContext.Request.Body;
    // 限制 读取 丢失
    var byts = new byte[request.ContentLength.Value];
    stream.Read(byts, 0, byts.Length);
    var postJson = Encoding.UTF8.GetString(byts);
    actionContext.HttpContext.Request.Body.Position = 0
    二、正确写法

    // 获取请求参数
    var request = context.HttpContext.Request;
    request.EnableBuffering();
    var postJson = string.Empty;
    if (request?.ContentLength > 0)
    {
    // 使用这个方式读取,并且使用异步
    StreamReader streamReader = new StreamReader(request.Body, Encoding.UTF8);
    postJson = streamReader.ReadToEndAsync().Result;
    }
    request.Body.Position = 0;

  • 相关阅读:
    springboot整合mybatis 异常 org.apache.ibatis.binding.BindingException: Invalid bound statement (not found):
    报时助手
    Huffman树费用
    动画效果
    工具和其他操作
    使用筛选器获取元素
    DOM操作
    属性和样式操作
    jQuery基础
    选择器
  • 原文地址:https://www.cnblogs.com/vsnb/p/15683795.html
Copyright © 2011-2022 走看看