2014-04-29 61 views
0

我试图从我的ASP .Net网络服务器获得JSON响应。我已阅读过类似的问题,并针对我的案例应用了答案,但仍无法从服务器获得JSON响应。它总是返回XML。iOS:从ASP .Net网络服务接收JSON响应

这里是我的web服务代码:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Script.Services; 
using System.Web.Services; 

[WebService(Namespace = "http://tempuri.org/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
[System.Web.Script.Services.ScriptService] 
public class TLogin : System.Web.Services.WebService { 

    static string LOGIN_STATUS_OK = "OK"; 
    static string LOGIN_STATUS_FAILD = "FAILED"; 

    public class LoginStatus { 
     public string status; 

     public LoginStatus() { 
      this.status = LOGIN_STATUS_FAILD; 
     } 

     public LoginStatus(string status){ 
      this.status = status; 
     } 
    } 

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

    [WebMethod] 
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public LoginStatus Login(string username, string password) { 
     return new LoginStatus(LOGIN_STATUS_OK); 
    } 
} 

Web.config文件:

<?xml version="1.0"?> 
<configuration> 
    <system.web> 
    <compilation debug="true" strict="false" explicit="true" targetFramework="4.5" /> 
    <httpRuntime targetFramework="4.5" requestPathInvalidCharacters="&lt;,&gt;,*,%,:,\,?" /> 
    <customErrors mode="Off"/> 
    <webServices> 
     <protocols> 
     <add name="HttpGet"/> 
     <add name="HttpPost"/> 
     </protocols> 
    </webServices> 
    </system.web> 
</configuration> 

iOS的HTTP请求代码:

NSURL *url = [NSURL URLWithString:@"http://192.168.1.20:8090/MyApplication/TuprasLogin.asmx/Login"]; 
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; 
[request setRequestMethod:@"POST"]; 
[request addRequestHeader:@"Content-Type" value:@"application/x-www-form-urlencoded"]; 
[request appendPostData:[post dataUsingEncoding:NSUTF8StringEncoding]]; 
[request setDelegate:self]; 
[request startAsynchronous]; 

缺少什么我在这里?

UPDATE

当我改变内容类型的建议:

[request addRequestHeader:@"Content-Type" value:@"application/json"]; 

并转换我的参数,以JSON消息为:

NSString *post = [[NSString alloc] 
       initWithFormat:@"{ \"username\" : \"%@\" , \"password\" : \"%@\" }", 
       self.textFieldUserName.text, self.textFieldPassword.text]; 

终于成功地接收JSON响应如下:

{"d":{"__type":"TLogin+LoginStatus","status":"OK"}} 

而且我发现,accep类型设置为JSON是没有必要的:

[request addRequestHeader:@"Accept" value:@"application/json"]; 

回答

1

我都面临着同样的问题早。作为参考,根据thisthis,如果你想从.ASMX使用JSON有必要:

  • Content-Typeapplication/json
  • 设置HTTP方法POST
0

来自我的登录代码的代码片段。基本上我在做什么是即时通讯创建一个授权字符串。并用base64进行编码。在那之后,我将授权添加为一个http头,并告诉服务器我想以JSON格式存储数据。当我做了即时填充会话并调用Asynchronus数据任务。完成后,您将获得一个NSdata对象,您需要使用正确的反序列化来填充JSON数组。

在我的情况下,我得到一个用户令牌,我需要验证每次,以便我不需要每次都需要推送用户名和密码时,我需要从我的API。

看低谷的代码,你将看看会发生什么的每一步:)

 NSString *userPasswordString = [NSString stringWithFormat:@"%@:%@", user.Username, user.Password]; 
     NSData * userPasswordData = [userPasswordString dataUsingEncoding:NSUTF8StringEncoding]; 
     NSString *base64EncodedCredential = [userPasswordData base64EncodedStringWithOptions:0]; 
     NSString *authString = [NSString stringWithFormat:@"Basic %@", base64EncodedCredential]; 

     NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; 

     // The headers, the authstring is a base64 encoded hash of the password and username. 
     [sessionConfig setHTTPAdditionalHeaders: @{@"Accept": @"application/json", @"Authorization": authString}]; 

     NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig]; 
     // Get the serverDNS 
     NSString *tmpServerDNS = [userDefault valueForKey:@"serverDNS"]; 
     // Request a datatask, this will execute the request. 
     NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString: [NSString stringWithFormat:@"%@/api/token",tmpServerDNS]] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) 
     {           
       NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response; 
       NSInteger statusCode = [HTTPResponse statusCode]; 
       // If the statuscode is 200 then the username and password has been accepted by the server. 
       if(statusCode == 200) 
       { 
        NSError *error = nil; 
        NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 

        user.token = [crypt EncryptString:[jsonArray valueForKey:@"TokenId"]]; 
        // Encrypt the password for inserting in the local database. 
        user.Password = [crypt EncryptString:user.Password]; 
        // Insert the user. 
        [core insertUser:user]; 

       } 
      }); 
     // Tell the data task to execute the call and go on with other code below. 
     [dataTask resume];