2014-04-29 59 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];