[英]how to receive Dictionary in WebAPI from javascript json
我在WebAPI中具有以下控制器功能:
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"}
您可以使用自定義模型活頁夾:
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庫來解析輸入字符串,然后將其轉換為Dictionary。 您可以實現其他解析邏輯。
請參閱此處...進行一些修改。 我認為您的困難在於如何調用URL。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.