Asp.net MVC中文件上传的参数转对象的方法

参照博友的.NET WebApi上传文件接口(带其他参数)实现文件上传并带参数,当需要多个参数时,不想每次都通过HttpContext.Request.Params去取值,就针对HttpRequestBase写了一个扩展方法,代码如下:

    public static class RequestHelper
    {
        public static T GetParamsModel<T>(this HttpRequestBase request) where T : new()
        {
            var model = new T();
            try
            {
                var properties = new T().GetType().GetProperties();
                var subNum = request.Params.Count;
                foreach (var p in request.Params.AllKeys)
                {
                    var property = properties.FirstOrDefault(x => x.Name == p);
                    if (null != property)
                    {
                        var val = TypeDescriptor.GetConverter(property.PropertyType).ConvertFromInvariantString(request.Params[p]);
                        property.SetValue(model, val, null);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return model;
        }
    }

在Controller里面调用:

var dto = HttpContext.Request.GetParamsModel<YourClassTypeName>();

 希望能够对初学者有一点用处,如果有更好的方法,也欢迎提出来,我也需要多学习一下。

posted on 2018-08-01 13:13  Hexy  阅读(248)  评论(0编辑  收藏  举报

导航