asp.net - 无法使用 AFNetworking 将 iOS 连接到 asp.net web 服务

标签 asp.net ios objective-c web-services afnetworking

我正在尝试从 iOS 连接到 asp.net Web 服务,但收到错误 500。如果使用 jQuery.ajax 从 Web 连接,则 Web 服务可以正常工作,但不能从 iOS 连接。是否需要在服务器端进行任何设置才能允许连接?可能某些安全设置不允许外部连接?我如何确保 Web 服务返回 json。当我尝试直接在浏览器中输入 url 时,我得到了 webservices 目录,并且可以调用 webservice,但出现错误。不过,网站上的一切都运行良好。这是我在 iOS 端使用的代码

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys: [NSDictionary dictionaryWithObjectsAndKeys:@"user", @"userName",@"test", @"password",nil],@"request",nil];
    AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:
    [NSURL URLWithString:@"http://www.server.com"]];
    //[client setDefaultHeader:@"contentType" value:@"application/json; charset=utf-8"];
    client.parameterEncoding = AFJSONParameterEncoding;
    NSMutableURLRequest *request =
    [client requestWithMethod:@"POST" path:@"/mobile/user.asmx/login" parameters:params];
    NSLog(@"request %@",request);
    AFJSONRequestOperation *operation =
    [AFJSONRequestOperation JSONRequestOperationWithRequest:request
                                                            success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
    {
          NSLog(@"response %@",response);
          NSLog(@"JSON: %@", [JSON valueForKeyPath:@"LoginResult"]);
          NSLog(@"Code: %@", [[[JSON valueForKeyPath:@"LoginResult"] valueForKeyPath:@"Code"] stringValue]);
          NSLog(@"FaultString: %@", [[JSON valueForKeyPath:@"LoginResult"] valueForKeyPath:@"FaultString"]);
             }
             failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON)
             {
                 NSLog(@"error opening connection %d %@",response.statusCode, error);
                 NSLog(@"request %@",request);
             }];
[operation start];
}

这是在网站上运行的代码

$('#signin').click(function (e) {
            e.preventDefault();
            var user = $('#user').val();
            var password = $('#password').val();
            var holdval = "<ul>";
            if (user == null || user == "")
                holdval += "<li>Provide user name</li>";

            if (password == null || password == "")
                holdval += "<li>Provide password</li>";

            holdval += "</ul>";
            if (holdval != "<ul></ul>") {
                $('#msg').show();
                $('#msg').html(holdval);
                return;
            }

            var temp = new User(user, password);
            $("#loader").show();
            var jsontxt = JSON.stringify({ user: temp });
            jQuery.ajax({
                type: "POST",
                url: "/mobile/user.asmx/login", //http://www.server.com

                contentType: "application/json; charset=utf-8", 
                data: jsontxt,
                dataType: "json",
                success: OnSuccess,
                error: OnError
            });
        });

更新

正如 Cory 建议的那样,我使用了wireshark 并检查了http 流量。事实证明该请求是一个 GET 请求,但我仍然无法使其正常工作。问题是网站请求传递带有用户名的 json 数据,而 afnetworking 仅传递用户名和密码

这是网站上的内容 http://www.server.com/user.asmx/loginuser {%22user%22:%22username%22,%22password%22:%22pass%22}

这是来自 iOS 的 http://www.server.com/user.asmx/loginuser?password=pass&user=username

在我看来,参数没有变成json

这是我在 iOS 上使用的更新代码

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://www.server.com/user.asmx/"]];
    [httpClient setParameterEncoding:AFJSONParameterEncoding];
    [httpClient setDefaultHeader:@"contentType" value:@"application/json; charset=utf-8"];
[httpClient getPath:@"loginuser" parameters:@{@"user":@"username",@"password":@"pass"} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Response: %@", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

如有任何建议,我们将不胜感激!

更新2 在上面的第一个代码中使用 afsjonrequestoperation 添加此代码后

[client setAuthorizationHeaderWithUsername:USERNAME password:USER_PASSWORD]; //setting authorization header
[client requestWithMethod:@"POST" path:@"login/" parameters:nil]; //parameter nil
 [request setHTTPMethod:@"GET"];

在开始操作后,我没有收到任何错误或响应,但如果我检查wireshark,我会收到 401 Unauthorized 和 html,表示凭据无效。我确信用户名和密码是正确的。我不确定这是否比以前更进一步。请让我知道你在想什么。再次感谢!

最佳答案

GET请求会序列化查询字符串中的参数,因为根据RFC 2616 , GET 请求不应包含实体主体。

对于您的特定情况,您可以使用上面的代码(像以前一样创建 POST 请求)来使其工作,但立即添加以下行:

[请求setHTTPMethod:@"GET"];

关于asp.net - 无法使用 AFNetworking 将 iOS 连接到 asp.net web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16674236/

相关文章:

c# - 在服务器端 Blazor 中使用 SignInManager

c# - 将跟踪 id/span id 设置为实际的关联 ID,以使用 OpenTelemetry for c# 跟踪请求

c# - 要在 asp.net c# 中解析的奇怪 Json

ios - 由于该应用程序崩溃,字典获得零值。展开可选值时意外发现 nil

ios - 有没有办法仍然使用 Xcode 4 调试 iPhone 5s

ios - 我可以在 iOS 中自定义 Twitter 工具包的登录按钮吗?

ios - 更改对象从NSUserDefaults获取

asp.net - 给我更好的主意在 asp.net 页面中做 Marquee 标记

显示 Controller 的 iOS 问题

ios - UITableView 附件 CheckMark 在单元格内移动标签