1. 程式人生 > >.net core 驗證器(filter)讀取post請求引數

.net core 驗證器(filter)讀取post請求引數

1.許可權(AuthorizationFilters)驗證器中讀取並只讀取有一次請求串的方法

      HttpRequest request = context.HttpContext.Request;
// post請求方式獲取請求引數,.net core 2.0 不支援.Form 直接獲取 
                    Stream stream = request.Body;
                    byte[] buffer = new byte[request.ContentLength.Value];
                    stream.Read(buffer, 0, buffer.Length);
                    string querystring = Encoding.UTF8.GetString(buffer);

2.當在動作過濾器(ActionFilter)或者需要多次讀取 request.body 的時候,.net core 可以通過呼叫request.EnableRewind()實現,可以重置讀取位置 ,但是要在許可權驗證器中新增,

  /// <summary>
        ///  請求驗證,當前驗證部分不要丟擲異常,ExceptionFilter不會處理
        /// </summary>
        /// <param name="context">請求內容資訊</param>
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            HttpRequest request = context.HttpContext.Request;
            request.EnableRewind();
            request.Body.Position = 0;
        }

然後可以在任意想要讀取的位置重複讀取

     /// <summary>
        ///  根據請求資訊返回請求串
        /// </summary>
        /// <param name="request">請求資訊</param>
        /// <returns>請求串</returns>
        public static string QueryString(HttpRequest request)
        {
            // post 請求方式獲取請求引數方式
            if (request.Method.ToLower().Equals("post"))
            {
                try
                {
                    // post請求方式獲取請求引數,.net core 2.0 不支援.Form 直接獲取 
                    Stream stream = request.Body;
                    byte[] buffer = new byte[request.ContentLength.Value];
                    stream.Read(buffer, 0, buffer.Length);
                    string querystring = Encoding.UTF8.GetString(buffer);
                    return querystring;
                }
                catch
                {
                    return string.Empty;
                }
            }
            else
            {
                return request.QueryString.Value;
            }
        }