zoukankan      html  css  js  c++  java
  • 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>();
    

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

  • 相关阅读:
    alpha冲刺9
    alpha冲刺8
    alpha冲刺7
    alpha冲6
    随堂小测-同学录
    alpha冲刺5
    任务3
    任务2
    任务1
    网站用户行为分析
  • 原文地址:https://www.cnblogs.com/gisser/p/9400653.html
Copyright © 2011-2022 走看看