【问题标题】:WebApi - Read GET parameters passed from jQuery GET to objectWebApi - 读取从 jQuery GET 传递到对象的 GET 参数
【发布时间】:2013-12-25 18:38:50
【问题描述】:

使用 jquery 调用 REST 服务时,我可以将 POJO 对象传递给 $.get(...) 调用,jquery 会将对象的属性序列化为 GET QueryString。

我的 REST 服务是使用 WebAPI 开发的,我想知道是否可以让它自动将查询字符串参数反序列化为对象。

更准确地说:

如果我有 POST 方法,我可以从消息正文中反序列化 json,如下所示

我有以下 jQuery 代码

var dataObj // my POJO
j$.post('/api/myserv', dataObj, function (data, status, jqXHR) {
    // ....

以及 WebApi 端点

' MyEntity class has same structure as POJO object
Public Function PostValue(<FromBody()> ByVal entity As MyEntity) As HttpResponseMessage 
    ' here I have entity instantiated and setup

当使用jquery get,并传递POJO对象时:

var dataObj // my POJO
j$.get('/api/myserv', dataObj, function (data, status, jqXHR) {
    // ....

这转化为

GET /api/myserv?prop1=val1&prop2=val2&...

在 WebApi 中,我想像使用 POST 一样实例化一个对象

' MyEntity class hadata from uri, s same structure as POJO object
Public Function GetValue(<FromURI()> ByVal entity As MyEntity) As HttpResponseMessage 
    ' but here the entity is null

为了能够阅读,我必须为 POJO 对象中的每个道具设置一个参数,例如

' MyEntity class hadata from uri, s same structure as POJO object
Public Function GetValue(prop1 As .., prop2 as ..., ) As HttpResponseMessage 

有没有什么方法可以从一个对象中读取所有参数,因为它是可能的;使用来自正文的 POST?

谢谢

【问题讨论】:

    标签: jquery json post asp.net-web-api get


    【解决方案1】:

    您可以在WebAPI 方法参数中的对象之前使用[FromUri]。在这里查看Parameter Binding

    如下设置你的 jquery 调用:

    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'json',
        data: { prop1: 1, prop2: "two" },
        success: function (result) {
            //handle
        }
    });
    

    【讨论】:

    • 其实我已经做到了(见我的问题),但没有奏效。但现在我又试了一次,它现在确实奏效了。奇怪的。感谢您的回答,这让我再试一次。
    猜你喜欢
    • 1970-01-01
    • 2013-03-26
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    • 2015-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多