如何从 Web API C# 方法中的操作参数获取所有字符串值我使用了以下代码:
public override void OnActionExecuting(HttpActionContext actionContext)
{
Dictionary<string, object> list = actionContext.ActionArguments;
for (int index = 0; index < list.Count; index++)
{
// need to all variables if the data type is string only
// input parameter might be list or model or int or string
list.ElementAt(index).Value;
}
}
如果输入参数是字符串,我需要编写通用方法来验证所有输入参数。输入参数可能是字符串或对象或整数或模型或模型中的列表...因此,我需要验证任何类型的输入以获取所有字符串参数
根据您的要求;这应该有效:
public override void OnActionExecuting(HttpActionContext actionContext)
{
var dictionary = actionContext.ActionArguments;
//key will contain the key, for convenience.
foreach (var key in dictionary.Keys)
{
//the value
var val = dictionary[key];
if (val is string)
{
//the value is runtime type of string
//do what you want with it.
}
}
}
至于后续,看看这个:https : //stackoverflow.com/a/20554262/2416958。结合“PrintProperties”方法,您应该会有所收获。
不过要注意循环引用;-)
修改后的版本(学分:https : //stackoverflow.com/a/20554262/2416958):
public void ScanProperties(object obj)
{
if (obj == null) return;
Type objType = obj.GetType();
PropertyInfo[] properties = objType.GetProperties();
foreach (PropertyInfo property in properties)
{
object propValue = property.GetValue(obj, null);
var elems = propValue as IEnumerable;
if (elems != null)
{
foreach (var item in elems)
{
ScanProperties(item);
}
}
else
{
// This will not cut-off System.Collections because of the first check
if (propValue is string)
{
//do you validation routine
}
ScanProperties(propValue);
}
}
}
并称之为:
public override void OnActionExecuting(HttpActionContext actionContext)
{
var dictionary = actionContext.ActionArguments;
//key will contain the key, for convenience.
foreach (var key in dictionary.Keys)
{
//the value
ScanProperties(dictionary[key]);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句