2017-05-12 23 views
2

收到字典中的WebAPI我在的WebAPI這個控制器功能:如何從JavaScript的JSON

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"} 
+2

由於您將數據發佈爲JSON正文,它不應該是'[FromBody]',而不是'[FromUri]'嗎? –

+0

@YeldarKurmangaliyev我對這個http請求使用GET方法。所以參數只能通過url發送 –

+0

好吧,我誤解了你。然後,如果您手動請求'/ your-api /?key1 = val1&key2 = val2&key3 = val3',則可以檢查您的API是否可以讀取此參數。如果是,請檢查您的JS在您的瀏覽器網絡標籤中發送給您的WebAPI的請求。 –

回答

3

您可以使用自定義的模型綁定:

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。你可以實現不同的解析邏輯。

+0

嗨。感謝您的回答。你的解決方案正在工作但我想問,這是最簡單的方法嗎?我應該使用ModelBinder作爲最佳實踐來處理這個問題嗎?是不是更容易接收這個參數作爲字符串,並解析它到控制器內的字典? –

+0

您可以在控制器內進行解析,但是無法重用您的代碼。 ModelBinder可重複使用,並將解析邏輯與控制器中的邏輯分開,這是一件好事。如果有人正在看你的方法,然後立即看到什麼參數是,不必關心解析等 –

+0

得到了。謝啦 –