2013-07-01 79 views
1

我有ASMX webservice,我想返回JSON格式的結果。當我的web方法沒有參數時,它工作正常。JSON結果在ASMX webservice

[WebService(Namespace = "http://www.arslanonline.com/")] 
    [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 AuthService : System.Web.Services.WebService { 

     public AuthService() { 

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

     [WebMethod] 
     [System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)] 
     public string Authenticate(string username, string password, string appId) 
     { 
      return ToJson("Hello World"); 
     } 

public static string ToJson(object obj) 
    { 
     return JsonConvert.SerializeObject(obj); 
    } 

[WebMethod] 
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public string Test() 
    { 
     return ToJson("Hello World"); 
    } 

當我打電話給我的測試Web方法這個方法它的做工精細

string url= "http://localhost:45548/Moves/AuthService.asmx/Test"; 
string dataToPost= ""; 
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
       request.Method = "POST"; 
       request.ContentType = "application/json;"; 
       request.BeginGetRequestStream(new AsyncCallback(DoHTTPPostRequestReady), new HttpWebRequestData<string>() 
       { 
        Request = request, 
        Data = dataToPost 
       }); 

,並返回我JSON結果。但對於正在採取一些參數我的第二個方法進行身份驗證,我請求這樣的

string url= "http://localhost:45548/Moves/AuthService.asmx/Authenticate"; 
    string dataToPost= "username=ABC&password=123&appid=1"; 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
        request.Method = "POST"; 
        request.ContentType = "application/json;"; 
        request.BeginGetRequestStream(new AsyncCallback(DoHTTPPostRequestReady), new HttpWebRequestData<string>() 
        { 
         Request = request, 
         Data = dataToPost 
        }); 

及其給我Not Found Error但是當我更改爲request.ContentType = "application/x-www-form-urlencoded";它工作正常,並返回給我的結果是XML但不是JSON格式。爲什麼發生這種情況可以請任何人告訴我的代碼中的毛刺在哪裏。

+0

您必須指定您需要在Web服務JSON類型結果 – rajansoft1

+0

退房此鏈接,事情可能的工作,它爲我工作http://www.codeproject.com/Questions/424178/Web- service-returning-json – rajansoft1

+0

@ rajansoft1:請再次檢查我的問題。我將響應格式指定爲JSON,並且我還將請求內容類型指定爲Application/json; –

回答

4

使用void作爲方法的返回類型。

[WebMethod] 
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
public void Test() 
{ 
    System.Web.HttpContext.Current.Response.Write(ToJson("Hello World")); 
}