我試圖從我的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="<,>,*,%,:,\,?" />
<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"];