是否可以从查询字符串中获取字典?

本文关键字:获取 字典 字符串 查询 是否 | 更新日期: 2023-09-27 17:54:16

我的控制器方法是这样的:

public ActionResult SomeMethod(Dictionary<int, string> model)
{
}

是否有可能调用此方法并仅使用查询字符串填充"模型"?我的意思是,输入像这样的东西:

ControllerName/SomeMethod?model.0=someText&model.1=someOtherText

在我们的浏览器地址栏。这可能吗?

编辑:

看来我的问题被误解了——我想绑定查询字符串,以便自动填充Dictionary方法参数。换句话说,我不想在我的方法中手动创建字典,而是让一些自动的。net绑定器帮我创建字典,这样我就可以像这样立即访问它:

public ActionResult SomeMethod(Dictionary<int, string> model)
{
    var a = model[SomeKey];
}

是否有一个自动装订器,足够聪明地做到这一点?

是否可以从查询字符串中获取字典?

. NET Core中,你可以使用以下语法(不需要自定义绑定器):

?dictionaryVariableName[KEY]=VALUE

假设你有这个作为你的方法:

public ActionResult SomeMethod([FromQuery] Dictionary<int, string> model)
然后调用以下URL:
?model[0]=firstString&model[1]=secondString

你的字典将被自动填充。与价值观:

(0, "firstString")
(1, "secondString")

对于。net Core 2.1,您可以很容易地做到这一点。

public class SomeController : ControllerBase
{
    public IActionResult Method([FromQuery]IDictionary<int, string> query)
    {
        // Do something
    }
}

和url

/Some/Method?1=value1&2=value2&3=value3

它将把它绑定到字典。您甚至不必使用参数名称查询

尝试自定义模型绑定器

      public class QueryStringToDictionaryBinder: IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var collection = controllerContext.HttpContext.Request.QueryString;
        var modelKeys =
            collection.AllKeys.Where(
                m => m.StartsWith(bindingContext.ModelName));
        var dictionary = new Dictionary<int, string>();
        foreach (string key in modelKeys)
        {
            var splits = key.Split(new[]{'.'}, StringSplitOptions.RemoveEmptyEntries);
            int nummericKey = -1;
            if(splits.Count() > 1)
            {
                var tempKey = splits[1]; 
                if(int.TryParse(tempKey, out nummericKey))
                {
                    dictionary.Add(nummericKey, collection[key]);    
                }   
            }                 
        }
        return dictionary;
    }
}
控制器动作中的

在模型上使用

     public ActionResult SomeMethod(
        [ModelBinder(typeof(QueryStringToDictionaryBinder))]
        Dictionary<int, string> model)
    {
        //return Content("Test");
    }

更具体的mvc模型绑定是将查询字符串构造为

/somemethod ?模型[0]。key = 1,模型[0]value = One&模型[1]。key = 2,模型[1]value =两个

自定义Binder只需遵循DefaultModelBinder

   public class QueryStringToDictionary<TKey, TValue> : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var modelBindingContext = new ModelBindingContext
        {
            ModelName = bindingContext.ModelName,
            ModelMetadata = new ModelMetadata(new EmptyModelMetadataProvider(), null, 
                null, typeof(Dictionary<TKey, TValue>), bindingContext.ModelName),
            ValueProvider = new QueryStringValueProvider(controllerContext)
        };
        var temp = new DefaultModelBinder().BindModel(controllerContext, modelBindingContext);
        return temp;
    }
}

在模型中应用自定义模型绑定器

     public ActionResult SomeMethod(
        [ModelBinder(typeof(QueryStringToDictionary<int, string>))] Dictionary<int, string> model)
    {
       // var a = model[SomeKey];
        return Content("Test");
    }