我在 WebAPI 中有这个 Controller 函数:
public class EntityController : APIController
{
[Route("Get")]
public HttpResponseMessage Get([FromUri]Dictionary<string, string> dic)
{ ... }
}
我的请求在 javascript 中看起来像这样:
{
"key1": "val1",
"key2": "val2",
"key3": "val3"
},
但解析失败。有没有办法在不编写太多代码的情况下完成这项工作?谢谢
我的完整要求:
http://localhost/Exc/Get?dic={"key1":"val1"}
您可以使用自定义模型 Binder :
public class DicModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType != typeof(Dictionary<string, string>))
{
return false;
}
var val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (val == null)
{
return false;
}
string key = val.RawValue as string;
if (key == null)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Wrong value type");
return false;
}
string errorMessage;
try
{
var jsonObj = JObject.Parse(key);
bindingContext.Model = jsonObj.ToObject<Dictionary<string, string>>();
return true;
}
catch (JsonException e)
{
errorMessage = e.Message;
}
bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Cannot convert value: " + errorMessage);
return false;
}
}
然后使用它:
public class EntityController : APIController
{
[Route("Get")]
public HttpResponseMessage Get([ModelBinder(typeof(DicModelBinder))]Dictionary<string, string> dic)
{ ... }
}
在 ModelBinder 中,我使用 Newtonsoft.Json 库解析输入字符串,然后将其转换为字典。您可以实现不同的解析逻辑。
我是一名优秀的程序员,十分优秀!