【WebApi】获取客户端参数的几种方式

1、通过FromBody获取  适合于json格式数据

[HttpPost]
        public async Task<ResponseResult> One([FromBody]TestRquest request)
        {
            int age = request.Age;
            string name = request.Name;
            Debug.WriteLine("name是:" + name);
            Debug.WriteLine("age是:" + age.ToString());
            return ResponseResult.GenSuccessResponse();

        }

 

2、通过FromForm  适用于获取form表单数据 【此属性仅在core中有效果】

public IActionResult Test5([FromForm]LoginInfo loginInfo)
        {
            return Json("参数验证通过");
        }

3、对于get请求的参数可用 FromUri或FromQuery获取

 public IActionResult Test5([FromQuery]LoginInfo loginInfo)
        {
            return Json("参数验证通过");
        }

 

4、通过HttpRequest 对象,来进行转化 获取

/// <summary>
        /// 字典类型转化为对象
        /// </summary>
        /// <param name="dic"></param>
        /// <returns></returns>
        public T DicToObject<T>(HttpRequest request) where T : new()
        {

            Dictionary<string, string> dic = new Dictionary<string, string>();
            if (request.HttpMethod.ToLower() == "post")
            {
                foreach (var item in request.Form.AllKeys.ToList())
                {
                    dic.Add(item, request.Form[item]);
                }
            }

            Type myType = typeof(T);
            T entity = new T();
            var fields = myType.GetProperties();
            string val = string.Empty;
            object obj = null;

            foreach (var field in fields)
            {
                if (!dic.ContainsKey(field.Name))
                    continue;
                val = dic[field.Name];

                object defaultVal;
                if (field.PropertyType.Name.Equals("String"))
                    defaultVal = "";
                else if (field.PropertyType.Name.Equals("Boolean"))
                {
                    defaultVal = false;
                    val = (val.Equals("1") || val.Equals("on")).ToString();
                }
                else if (field.PropertyType.Name.Equals("Decimal"))
                    defaultVal = 0M;
                else
                    defaultVal = 0;

                if (!field.PropertyType.IsGenericType)
                    obj = string.IsNullOrEmpty(val) ? defaultVal : Convert.ChangeType(val, field.PropertyType);
                else
                {
                    Type genericTypeDefinition = field.PropertyType.GetGenericTypeDefinition();
                    if (genericTypeDefinition == typeof(Nullable<>))
                        obj = string.IsNullOrEmpty(val) ? defaultVal : Convert.ChangeType(val, Nullable.GetUnderlyingType(field.PropertyType));
                }

                field.SetValue(entity, obj, null);
            }

            return entity;
        }

 

posted @ 2021-01-25 10:54  狼窝窝  阅读(841)  评论(0)    收藏  举报