2012-09-10 54 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