.net core 在服务器端获取api传递的参数
在 ActionFilterAttribute 的OnActionExecutionAsync 中使用如下代码从流中读取用户参数
//从文件流中读取传递测参数 using (var ms = new MemoryStream()) { context.HttpContext.Request.Body.Seek(0, 0);//将读取指针迻到开始位置 context.HttpContext.Request.Body.CopyTo(ms); var b = ms.ToArray(); var postParamsString = Encoding.UTF8.GetString(b); }
虽然以前就知道是从流中读取,但是.net core的比较难找,找了将近两个小时才找到从流中读取参数的方法,关键是这句:context.HttpContext.Request.Body.Seek(0, 0);不然读取的内容为空
完整代码
public class SignValidateAttribute : ActionFilterAttribute { #region /// <summary> /// /// </summary> /// <param name="context"></param> /// <param name="next"></param> /// <returns></returns> public async override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { //从文件流中读取传递测参数 using (var ms = new MemoryStream()) { context.HttpContext.Request.Body.Seek(0, 0); context.HttpContext.Request.Body.CopyTo(ms); var b = ms.ToArray(); var postParamsString = Encoding.UTF8.GetString(b); await next(); } } /// <summary> /// /// </summary> /// <param name="context"></param> /// <param name="next"></param> /// <returns></returns> public override Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) { //string dataJson = GetContextJson(context.); return base.OnResultExecutionAsync(context, next); } #endregion }
将偷懒进行到极致,是一个程序员的基本素养