Objective-C Post JSON to WebApi Controller



我有以下javascript函数,它将数据发布回 ASP.NET Web Api控制器:

var d = {
    NorthEastPoint: {
        Latitude: boundingBox.ne.lat,
        Londitude: boundingBox.ne.lng
    },
    SouthWestPoint: {
        Latitude: boundingBox.sw.lat,
        Londitude: boundingBox.sw.lng
    },
    CurrentLocation: {
        Latitude: 0,
        Londitude: 0
    },
    IncludeFullImage: false
};
console.log(JSON.stringify(d));
var endPoint = 'http://127.0.0.1/api/Search/';
$.ajax({
    url: endPoint,
    type: 'POST',
    data: d,
    dataType: 'json',
    crossDomain: true,
    success: function (data) {
    },
    statusCode: {
        404: function (content) {
            return 'cannot find resource';
        },
        505: function (content) {
            return 'internal server error';
        }
    },
    error: function (req, status, errorObj) {
        // handle status === "timeout"
        // handle other errors
    }
});

这篇文章工作正常。我正在尝试使用NSURLConnection在Objective-C中复制ajax帖子。

这是我创建json的Objective-C代码:

NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
NSDictionary *NorthEastPoint = [[NSDictionary alloc] initWithObjectsAndKeys:[[NSNumber alloc] initWithFloat:_pointOneLat],@"Latitude",
                                [[NSNumber alloc] initWithFloat:_pointOneLon],@"Londitude",nil];
NSDictionary *SouthWestPoint = [[NSDictionary alloc] initWithObjectsAndKeys:[[NSNumber alloc] initWithFloat:_pointTwoLat],@"Latitude",
                                [[NSNumber alloc] initWithFloat:_pointTwoLon],@"Londitude",nil];
NSDictionary *CurrentLocation = [[NSDictionary alloc] initWithObjectsAndKeys:[[NSNumber alloc] initWithFloat:_currentLat],@"Latitude",
                                [[NSNumber alloc] initWithFloat:_currentLon],@"Londitude",nil];
[dict setObject:NorthEastPoint forKey:@"NorthEastPoint"];
[dict setObject:SouthWestPoint forKey:@"SouthWestPoint"];
[dict setObject:CurrentLocation forKey:@"CurrentLocation"];
[dict setObject:@"false" forKey:@"IncludeFullImage"];

NSError *writeError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&writeError];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"JSON Output: %@", jsonString);

上面的输出是:

JSON Output: {
  "NorthEastPoint" : {
    "Londitude" : 1.388894,
    "Latitude" : 57.49198
  },
  "CurrentLocation" : {
    "Londitude" : -6.12792,
    "Latitude" : 53.24554
  },
  "SouthWestPoint" : {
    "Londitude" : -5.642355,
    "Latitude" : 52.30821
  },
  "IncludeFullImage" : "false"
}

然后,我尝试使用以下代码将 json 发布到我的 WebApi 控制器:

NSURL * url = [NSURL URLWithString:@"http://172.20.10.5/apisite/api/Search"];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:jsonData];
    theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (theConnection) {
        [self.delegate searchDidStart];
        // Create the NSMutableData to hold the received data.
        // receivedData is an instance variable declared elsewhere.
        self.receivedData = [[NSMutableData alloc]init];
    } else {
    }

发布控制器后,我可以看到我的帖子成功,因为命中了断点,但是模型数据没有填充。我的控制器方法如下所示:

public async Task<IEnumerable<PlaceDTO>> Post(BoxSearchParam model) {
    // Do stuff
}

BoxSearchParam定义为:

public class BoxSearchParam
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="BoxSearchParam"/> class.
        /// </summary>
        public BoxSearchParam()
        {
            this.NorthEastPoint = new MapPoint();
            SouthWestPoint = new MapPoint();
            CurrentLocation = new MapPoint();
            MaximumSearchRadius = int.Parse(ConfigurationManager.AppSettings["MaxDistanceBetweenPoints"]);
        }
        /// <summary>
        /// Gets or sets the north west point.
        /// </summary>
        public MapPoint NorthEastPoint { get; set; }
        /// <summary>
        /// Gets or sets the south east point.
        /// </summary>
        public MapPoint SouthWestPoint { get; set; }
        /// <summary>
        /// Gets or sets the current location.
        /// </summary>
        public MapPoint CurrentLocation { get; set; }
        /// <summary>
        /// Gets or sets the maximum search radius.
        /// </summary>
        public int MaximumSearchRadius { get; internal set; }
        /// <summary>
        /// Gets or sets a value indicating whether include full image.
        /// </summary>
        public bool IncludeFullImage { get; set; }
    }

MapPoint 定义为:

public class MapPoint
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MapPoint"/> class.
        /// </summary>
        public MapPoint()
        {
            Londitude = 0;
            Latitude = 0;
        }
        /// <summary>
        /// Gets or sets the londitude.
        /// </summary>
        public decimal Londitude { get; set; }
        /// <summary>
        /// Gets or sets the latitude.
        /// </summary>
        public decimal Latitude { get; set; }
    }

我在发布数据时哪里出了问题,从我所看到的情况来看,我已经在 javascript 帖子中复制了该功能,所以我不知道为什么它不起作用。

更改行[dict setObject:@"false" forKey:@"IncludeFullImage"];

自 [dict [NSNumber numberWithBool:NO] forKey:@"IncludeFullImage"];

然后重试。希望有帮助。

最新更新