协思

协作、思考、感悟、进步

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
    public static class HttpRequestExtension
    {
        /// <summary>
        /// 依据Request Body构建指定的实体类型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T ReadEntity<T>(this HttpRequestBase request) where T : class
        {
            if (request.InputStream.Length == 0) throw new Exception("request body must be not null");

            try
            {
                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T));
                request.InputStream.Position = 0;
                return jsonSerializer.ReadObject(request.InputStream) as T;
            }
            catch (SerializationException)
            {
                return null;
            }
        }
    }

 

posted on 2013-02-17 11:04  协思  阅读(351)  评论(0编辑  收藏  举报