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

我的控制器方法如下所示:

public ActionResult SomeMethod(Dictionary model) { } 

是否可以调用此方法并仅使用查询字符串填充“模型”? 我的意思是,键入这样的东西:

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

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

编辑:

看来我的问题被误解了 – 我想绑定查询字符串,以便自动填充Dictionary方法参数。 换句话说 – 我不想在我的方法中手动创建字典,但有一些自动化.NET绑定器来形成我,所以我可以立即访问它,如下所示:

 public ActionResult SomeMethod(Dictionary model) { var a = model[SomeKey]; } 

是否有自动装订器,足够智能这样做?

在ASP.NET Core中,您可以使用以下语法(无需自定义绑定器):

 ?dictionaryVariableName[KEY]=VALUE 

假设你有这个方法:

 public ActionResult SomeMethod([FromQuery] Dictionary model) 

然后调用以下URL:

 ?model[0]=firstString&model[1]=secondString 

然后会自动填充您的字典。 有价值:

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

已经有一个字典 – 它叫做Request.QueryString。

尝试定制模型粘合剂

  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(); 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 model) { //return Content("Test"); } 

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

/somemethod?model[0].Key=1&model[0].Value=One&model[1].Key=2&model[1].Value=Two

Custom Binder只需遵循DefaultModelBinder

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

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

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

对于.NET Core 2.1,您可以非常轻松地完成此操作。

 public class SomeController : ControllerBase { public IActionResult Method([FromQuery]IDictionary query) { // Do something } } 

和url

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

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

使用HttpUtility.ParseQueryString()

看看这是一个关于在C#中使用正则表达式解析查询字符串的一个很好的例子