2013-04-29 47 views
1

我從零開始創建了一個VS 2012 MVC API項目,加載了Nuget「WebApiContrib.Formatting.Jsonp」,添加了一個路由,格式化程序,並嘗試將參數作爲序列化的JSON作爲JSONP請求發送。如何識別或訪問控制器中的這些參數?如何在JSONP中綁定MVC API參數獲取?

WebApiConfig:

config.Routes.MapHttpRoute(
    name: "DefaultApi", 
    routeTemplate: "api/{controller}/{id}/{format}", 
    defaults: new { id = RouteParameter.Optional, 
     format = RouteParameter.Optional } 
); 
config.Formatters.Insert(0, new JsonpMediaTypeFormatter()); 

API方法:

public IEnumerable<string> Get() 
{ 
    return new string[] { "value1", "value2" }; 
} 

JQuery的:

$.ajax({ 
    type: 'GET', 
    url: '/api/Values', 
    data: JSON.stringify({ "message": "\"Hello World\"" }), 
    contentType: "application/json; charset=utf-8", 
    dataType: 'jsonp', 
    success: function (json) { 
     console.dir(json.sites); 
    }, 
    error: function (e) { 
     console.log(e.message); 
    } 
}); 

我已經試過修改API方法包括:

Get([FromUri] string value) 
Get([FromBody] string value) 
Get(CustomClass stuff) 
Get([FromUri] CustomClass stuff) 
Get([FromBody] CustomClass stuff) 

凡CustomClass被定義爲:

public class CustomClass 
{ 
    public string message { get; set; } 
} 

到目前爲止,這些都不產生任何東西,但空的參數。我應該如何連接查詢字符串中發佈的對象的這些參數?

編輯:

我可以通過修改JQuery的AJAX是絕招吧:

data: {"value":JSON.stringify({ "message": "\"Hello World\"" })} 

的,我可以去字符串化的[FromUri] string value拿到我的強類型的對象。

不過,我期待數據聯編程序將參數解碼爲強類型對象。什麼技術使這發生?

+0

目前,確切的解決方案不太確定,但嘗試更改API參數名稱爲Id。即Get([FromUri]字符串ID)。請參閱它是否有效。可能聽起來沒有語境,但只是試一試。 – Shubh 2013-04-29 06:19:19

回答

1

你正在一個GET請求,並在GET要求的情況下,沒有只有URI。所有你提供的$.ajax()呼叫的數據將被投入到URI,例如您的編輯版本將產生URI是這樣的:

.../api/Values?value=%7B%22message%22%3A%22%5C%22Hello%20World%5C%22%22%7D 

(注意,JSON也將URL編碼)。

現在在網絡API的URI參數正在被結合利用的ModelBinderParameterBinding,這意味着網絡API將不使用任何MediaTypeFormatter(其輸出複雜類型),但一個ModelBinder/ValueProvider(在這種情況下將輸出一個簡單類型 - 字符串)。

您可以通過實現自定義ModelBinder(請記住從ASP.NET Web API命名空間使用適當的類和接口而不是ASP來接近您的場景。NET MVC的):

public class JsonModelBinder : IModelBinder 
{ 
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) 
    { 
     ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); 
     if (valueProviderResult == null) 
      return false; 

     bindingContext.Model = JsonConvert.DeserializeObject(valueProviderResult.AttemptedValue, bindingContext.ModelType); 

     return true; 
    } 
} 

public class JsonModelBinderProvider : ModelBinderProvider 
{ 
    public override IModelBinder GetBinder(HttpActionContext actionContext, ModelBindingContext bindingContext) 
    { 
     return new JsonModelBinder(); 
    } 
} 

而且它與ModelBinderAttribute連接到您的參數:

public IEnumerable<string> Get([ModelBinder(typeof(JsonModelBinderProvider))]CustomClass value) 
{ 
    return new string[] { "value1", "value2" }; 
} 

您可以找到有關的主題在這裏更多的細節: