Response.Write() in WebService

前端 未结 2 2188
庸人自扰
庸人自扰 2020-12-19 02:58

I want to return JSON data back to the client, in my web service method. One way is to create SoapExtension and use it as attribute on my web method, etc. Anoth

相关标签:
2条回答
  • 2020-12-19 03:28

    This works for me:

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public void ReturnExactValueFromWebMethod(string AuthCode)
    {
        string r = "return my exact response without ASP.NET added junk";
        HttpContext.Current.Response.BufferOutput = true;
        HttpContext.Current.Response.Write(r);
        HttpContext.Current.Response.Flush();
    }
    
    0 讨论(0)
  • 2020-12-19 03:32

    Why don't you return an object and then in your client you can call as response.d?

    I don't know how you are calling your Web Service but I made an example making some assumptions:

    I made this example using jquery ajax

    function Test(a) {
    
                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "TestRW.asmx/HelloWorld",
                        data: "{'id':" + a + "}",
                        dataType: "json",
                        success: function (response) {
                            alert(JSON.stringify(response.d));
    
                        }
                    });
                }
    

    And your code could be like this (you need to allow the web service to be called from script first: '[System.Web.Script.Services.ScriptService]'):

        [WebMethod]
        public object HelloWorld(int id)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("message","success");
    
            return dic;
        }
    

    In this example I used dictionary but you could use any object with a field "message" for example.

    I'm sorry if I missunderstood what you meant but I don't really understand why you want to do a 'response.write' thing.

    Hope I've helped at least. :)

    0 讨论(0)
提交回复
热议问题