How to get all string values from action arguments in Web API C# method

白昼怎懂夜的黑 提交于 2021-02-05 10:54:26

问题


How to get all string values from action arguments in Web API C# method I have used this code:

 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;

     }
 }

I need to write generic method to validate all input parameters if the input parameter is string. Input parameters might be string or object or int or model or list in model...So, i need to validate any kind of input to get all string parameters


回答1:


On your request; this should work:

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.
        }
    }
}

As for the follow up, have a look at this: https://stackoverflow.com/a/20554262/2416958 . Combine with the "PrintProperties" method, and you should get somewhere.

Be aware of cyclic references though ;-)

Modified version (credits: https://stackoverflow.com/a/20554262/2416958):

note: is not protected against cyclic references.

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);
        }
    }
}

And call it like:

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]);
    }
}


来源:https://stackoverflow.com/questions/64021621/how-to-get-all-string-values-from-action-arguments-in-web-api-c-sharp-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!