asp.net - 如何将 JSON POST 从 iOS 设备发送到 ASP.NET URL

标签 asp.net ios json web-services

我正在开发一个需要与 Windows 服务器共享数据的应用程序。我在网上查看了一些示例,并提出了下面列出的实现。虽然 iOS 代码和网络服务独立工作得很好,但我不知道如何将它们连接在一起。我见过的所有示例都没有显示网络服务的 URL(或者至少没有以允许我弄清楚发生了什么的方式)。请查看我的 ServerURL 值并提出建议。我相信它应该在某处包含入口点“doSomething”的名称,但我不知道语法应该是什么样子。我已经尝试过 http://texas/WebSite3/Service.asmx/doSomethinghttp://texas/WebSite3/Service.asmx?op=doSomething 但似乎都没有工作。如果存在任何其他问题,请告诉我。

我假设一旦我让它在我的本地系统上运行,我就可以用完整的域名替换 Texas。

这是 iOS 代码:

-(void)checkWithServer {
// Create the POST request payload.
    NSDictionary *tmp = [[NSDictionary alloc]initWithObjectsAndKeys:
                     @"test@gmail.com", @"email",
                     @"John Doe", @"name",
                     nil];
    NSError *error;
    NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];

    NSString *serverURL = @"http://texas/WebSite3/Service.asmx";

// Create the POST request to the server.
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:serverURL]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", [postdata length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postdata];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    [conn start];
}

这是与之对话的网络服务:

    [WebService(Namespace = "http://texas/WebSite3")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class Service : System.Web.Services.WebService
    {
        public Service () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string doSomething(string msg)
    {
        byte[] buffer = GetBytes(msg);
        XmlReader reader = System.Runtime.Serialization.Json.JsonReaderWriterFactory.CreateJsonReader(buffer, System.Xml.XmlDictionaryReaderQuotas.Max);
        XElement root = XElement.Load(reader);

        string result = "{\"result\":\"none\"}";

        return result;
    }

最佳答案

在 Axeva 的帮助下,这就是我想出的办法。

iOS 代码:

-(void)checkWithServer {
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    NSURL *postURL = [NSURL URLWithString: @"http://texas/WebSite3/Service.asmx/doSomething"];
    NSDictionary *jsonDict = [[NSDictionary alloc] initWithObjectsAndKeys:
                              @"test@gmail.com", @"email",
                              @"John Doe", @"name",
                              nil];

    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: postURL
                                                           cachePolicy: NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval: 60.0];

    [request setHTTPMethod: @"POST"];
    [request setValue: @"application/json" forHTTPHeaderField: @"Accept"];
    [request setValue: @"application/json; charset=utf-8" forHTTPHeaderField: @"content-type"];
    [request setHTTPBody: jsonData];

    [NSURLConnection sendAsynchronousRequest: request
                                       queue: queue
                           completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error) {
                               if (error || !data) {
                                   // Handle the error
                               } else {
                                   // Handle the success
                               }
                           }
     ];
}

网络服务器代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Xml;
using System.Xml.Linq;
using System.Data;
using System.Data.SqlClient;

[WebService(Namespace = "http://texas/WebSite3")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment   the following line. 
[System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
    public Service () {

    //Uncomment the following line if using designed components 
    //InitializeComponent(); 
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string doSomething(string email, string name)
    {
        return "{\"name\": \"" + name + "\", \"email\": \"" + email + "\"}";
    }
}

显然,网络服务器足够聪明,可以将 JSON 分开并分配变量名称和电子邮件。

关于asp.net - 如何将 JSON POST 从 iOS 设备发送到 ASP.NET URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15904622/

相关文章:

JavaScript 无法在我的服务器上运行

c# - 为什么在 IIS 7 服务器上在本地机器上工作正常时找不到类型或命名空间?

asp.net - 向 ASP.NET 中的注册用户发送电子邮件

c# - 将其作为循环运行时,我应该将 Open() 和 Close() 放在循环外还是循环内?

ios - Xcode 10.2,Swift 5,使用 Release Scheme 构建程序时命令 compileSwift 失败

c# - 序列化包含字典的对象,以便字典键/值呈现为包含对象的一部分

asp.net - IValidatableObject 验证方法在 DataAnnotations 失败时触发

ios - Xcode Scheme 中的调试可执行选项

ios - 用于在图像上叠加文本和图形的图形库和函数

javascript - 如何通过正则表达式仅对 JSON 键进行着色?