2012-09-10 111 views
0

我正在嘗試將POST數據轉換爲另一個域中的Asp.Net Web API。我需要支持IE9/8,所以CORS不會削減它。當我做出這樣的呼籲:從Asp.Net Web API中的JSONP請求獲取數據

$.ajax({ 
type: "GET", 
url: "http://www.myotherdomain.com/account", 
data: "{firstName:'John', lastName:'Smith'}", 
contentType: "application/json; charset=utf-8", 
dataType: "jsonp", 
success: function(msg) { 
    console.log(msg); 
}, 
error: function(x, e) { 
    console.log(x); 
} 
});​ 

它使GET請求:

http://www.myotherdomain.com/account? 
    callback=jQuery18008523724081460387_1347223856707& 
    {firstName:'John',%20lastName:'Smith'}& 
    _=1347223856725 

我實現this JSONP Formatter for ASP.NET Web API和我的服務器以正確的格式JSONP響應響應。我不明白如何註冊一個路線來消費一個賬戶對象。

config.Routes.MapHttpRoute(
    name: "Account", 
    routeTemplate: "account", 
    defaults: new { controller = "account", account = RouteParameter.Optional } 
); 

如何反序列化querystring參數中的對象而沒有名稱?

回答

2

而不是使用JSON,你可以發送參數作爲查詢字符串值。讓我們假設你有以下型號:

public class User 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
} 

及以下API控制器:

public class AccountController : ApiController 
{ 
    public HttpResponseMessage Get([FromUri]User user) 
    { 
     return Request.CreateResponse(HttpStatusCode.OK, new { foo = "bar" }); 
    } 
} 

可能這樣被消耗:

$.ajax({ 
    type: 'GET', 
    url: 'http://www.myotherdomain.com/account?callback=?', 
    data: { firstName: 'John', lastName: 'Smith' }, 
    dataType: 'jsonp', 
    success: function (msg) { 
     console.log(msg); 
    }, 
    error: function (x, e) { 
     console.log(x); 
    } 
}); 
+0

啊,我怎麼註冊的路線爲此在我的WebApiConfig.cs? – Greg

+0

您已經使用'config.Routes.MapHttpRoute'方法完成了該操作。 –

+0

感謝,從你的例子,我打我的'Get'函數,但我的'用戶'對象有一個空'FirstName'和'LastName',任何想法? – Greg