2013-07-01 82 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")); 
}