POST Http请求的正文部分为null

时间:2014-07-11 11:14:55

标签: ios .net post afnetworking-2 frombodyattribute

我使用AFNetworking框架将一些数据发送到.Net后端。我使用POST:parameters:success:failure:方法。

.net后端正在使用FromBody属性

读取数据
 [System.Web.Mvc.HttpPost]
        public HttpResponseMessage Post([FromBody] string objCourseData, string securityToken, string appVer, string deviceDesc, string deviceOSDesc)

但它接收为null。我已尝试使用PHP,我可以在$_POST对象中看到我的正文数据(我无法在$HTTP_RAW_POST_DATA中看到它)。可能是什么问题?

我发送的数据是JSON对象。

1 个答案:

答案 0 :(得分:2)

我不使用AFNetworking,但使用本机代码很简单:

NSString *urlString = @"http://www.urlpost.com";

//setting request
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:5];
[request setHTTPMethod:@"POST"];

//setting post body with JSON data
NSMutableDictionary *postDictionary = [NSMutableDictionary dictionary];
//set the data of your json
[postDictionary setValue:@"some value" forKey:@"myKey"];
NSError *jsonError;

//transform NSMutableDictionary in JSON data
NSData *postData = [NSJSONSerialization dataWithJSONObject:postDictionary
                                                   options:0
                                                     error:&jsonError];

if (!jsonError) {
    //set POST body
    [request setHTTPBody:postData];
}

//Here is the code for the post:
[[[NSURLSession sharedSession] dataTaskWithRequest:request
                                 completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

    if (!error) {
        //No errors, post done
        NSLog(@"POST done!");
    } else { 
       //error handling here 
    }
}] resume];