C# ASP.NET webapi 解析所有的引數BASE64加密的串
例如:加密前:http://xxxxxxxx/xxx/xxx?a=1&b=2&c=3 加密後http://xxxxxxxx/xxx/xxx?P=YT0xJmI9MiZjPTM=
在api建立模型類前,進行攔截,先將串解析,再根據解析的串對模型類的屬性反射賦值。
public class ActionParamModelBinder : IModelBinder { public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { try { //反射建立模型類 modelType模型類的型別 bindingContext.ModelType是哪個模型類 Type modelType = bindingContext.ModelType; Assembly assembly = Assembly.GetExecutingAssembly(); //建立模型類的實體類 Mode是實體類 object model = assembly.CreateInstance(modelType.FullName);
string method = actionContext.Request.Method.ToString().ToUpper(); //獲取傳送的所有引數 //get方式 IEnumerable<KeyValuePair<string, string>> querystrings = actionContext.Request.GetQueryNameValuePairs();
//post方式 var requestForm = HttpContext.Current.Request.Form; if (method == "POST" && requestForm.AllKeys.Length > 0) { Dictionary<string, string> postForm = new Dictionary<string, string>(); foreach (var key in requestForm.AllKeys) { postForm.Add(key, requestForm[key]); }
querystrings = postForm; }
//只取P的引數 string value = ""; if (method == "POST" && requestForm.AllKeys.Length > 0)//post方式 { if (requestForm != null && requestForm["P"] != null) { value = requestForm["P"]; } } else//get方式 { if (querystrings.Any(i => i.Key == "P")) { if (querystrings.Any(i => i.Key == "P")) { value = querystrings.First(i => i.Key == "P").Value == null ? "" : querystrings.First(i => i.Key == "P").Value; } } }
//P的value是否是base64型別的字串 if (String2Base64.IsBase64(value)) { querystrings = String2Base64.DecodeParams2Dictionary(value); }
foreach (var querystring in querystrings) {
BindingFlags flag = BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance;
PropertyInfo pi = modelType.GetProperty(querystring.Key, flag);
if (pi != null) { pi.SetValue(model, querystring.Value); } }
bindingContext.Model = model; } catch (Exception e) { Intmes.Log.Logger.Error(e.StackTrace); } return true; }