【问题标题】:Get Data From JSONP Request In Asp.Net Web Api在 Asp.Net Web Api 中从 JSONP 请求获取数据
【发布时间】:2012-09-02 20:56:09
【问题描述】:

我正在尝试将 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 }
);

如何从没有名称的查询字符串参数中反序列化对象?

【问题讨论】:

    标签: asp.net-mvc iis asp.net-web-api jsonp


    【解决方案1】:

    您可以将参数作为查询字符串值发送,而不是使用 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);
        }
    });
    

    【讨论】:

    • 啊,如何在我的 WebApiConfig.cs 中为此注册路由?
    • 您已经使用config.Routes.MapHttpRoute 方法完成了这项工作。
    • 谢谢,从你的例子来看,我正在使用我的Get 函数,但我的user 对象有一个空的FirstNameLastName,有什么想法吗?
    • 我在属性后丢失了{ get; set; },谢谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 2016-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多