Convert custom action filter for Web API use?

前端 未结 2 1174
青春惊慌失措
青春惊慌失措 2020-12-23 21:56

I found a really nice action filter that converts a comma-separated parameter to a generic type list: http://stevescodingblog.co.uk/fun-with-action-filters/

I would

2条回答
  •  春和景丽
    2020-12-23 22:37

    Here is another way:

    public class ConvertCommaDelimitedList : CollectionModelBinder
    {
        public override bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
       {
           var _queryName = HttpUtility.ParseQueryString(actionContext.Request.RequestUri.Query)[bindingContext.ModelName];
            List _model = new List();
            if (!String.IsNullOrEmpty(_queryName))
                _model = _queryName.Split(',').ToList();
    
            var converter = TypeDescriptor.GetConverter(typeof(T));
            if (converter != null)
                bindingContext.Model = _model.ConvertAll(m => (T)converter.ConvertFromString(m));
            else
                bindingContext.Model = _model;
    
            return true;
        }
    }
    

    And list your param in the ApiController ActionMethod:

    [ModelBinder(typeof(ConvertCommaDelimitedList))] List StudentIds = null)
    

    Where StudentIds is the querystring param (&StudentIds=1,2,4)

提交回复
热议问题