繁体   English   中英

JSON结果在ASMX webservice中

[英]JSON result in ASMX webservice

我有ASMX webservice,我想以JSON格式返回结果。 当我的web方法没有参数时,它工作正常。

    [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");
    }

当我打电话给我的测试网方法这样的方式它的工作正常

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结果。 但对于我的第二种方法Authenticate,我正在请求一些参数

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格式。 为什么会发生这种情况可以请任何人告诉我代码中的故障在哪里。

使用void作为方法的返回类型。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM