我正在尝试将POST
数据传输到我的另一个域上的Asp.Net Web API。我需要支持IE9 / 8,因此CORS
不会删减。当我打这样的电话时:
$.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参数反序列化对象?
代替使用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);
}
});