mvc web api filter 多个筛选器同时读取post 内容时为空的解决方案

读取 post 请求内容,最方便的就是使用 stream 了(如下),单个 filter 没问题,但是如果同一个 controller 附加
两个 filter 就有问题了,第一个 filter 可以正常读取内容,但是之后的在读 stream 的长度就是 0 了。


public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext context)
{
var task = context.Request.Content.ReadAsStreamAsync();
var content = string.Empty;
using (System.IO.Stream sm = task.Result)
{
if (sm != null)
{
   sm.Seek(0, SeekOrigin.Begin);
   int len = (int) sm.Length;
   byte[] inputByts = new byte[len];
   sm.Read(inputByts, 0, len);
   sm.Close();
   content = Encoding.UTF8.GetString(inputByts);
}
}
}


试了好几种办法:想用 clone 复制一个 stream 结果没有成功。


最后解决方法是:
1.将 stream 读到 byte[] 数组中
2.将 byte[] 在转成 string 
3.将每个 filter 中读取 post 内容的位置均写成这种形式,就都可以读到了


代码实例:
//读取post内容
var task = context.Request.Content.ReadAsStreamAsync();
var content = string.Empty;
var sm = task.Result;
sm.Seek(0, SeekOrigin.Begin);//设置流的开始位置
var bytes = sm.ToByteArray();
content = bytes.ToStr();


用到的几个扩展方法:
1.stream 转 byte[]
/// <summary>
/// Stream Stream 转换为 byte 数组
/// </summary>
/// <returns></returns>
public static byte[] ToByteArray(this Stream stream)
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
// 设置当前流的位置为流的开始 
stream.Seek(0, SeekOrigin.Begin);
return bytes;
}


2.byte[] 转 string
/// <summary>
/// 转换为 string,使用 Encoding.Default 编码
/// </summary>
/// <returns></returns>
public static string ToStr(this byte[] arr)
{
return System.Text.Encoding.Default.GetString(arr);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值