How to get JSON response from a 3.5 asmx web service

后端 未结 4 1406
梦谈多话
梦谈多话 2020-11-27 07:03

I have the following method:

using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using         


        
4条回答
  •  借酒劲吻你
    2020-11-27 07:04

    I faced the same issue, and included the below code to get it work.

    [WebMethod]
    [ScriptMethod(UseHttpGet=true ,ResponseFormat = ResponseFormat.Json)]
    public void HelloWorld()
    {
        Context.Response.Clear();
        Context.Response.ContentType = "application/json";
        Context.Response.Write("Hello World");
        //return "Hello World";
    }
    

    Update:

    To get a pure json format, you can use javascript serializer like below.

    public class WebService1 : System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(UseHttpGet=true ,ResponseFormat = ResponseFormat.Json)]
        public void HelloWorld()
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            Context.Response.Clear();
            Context.Response.ContentType = "application/json";           
            HelloWorldData data = new HelloWorldData();
            data.Message = "HelloWorld";
            Context.Response.Write(js.Serialize(data));
    
    
        }
    }
    
    public class HelloWorldData
    {
       public String Message;
    }
    

    However this works for complex types, but string does not show any difference.

提交回复
热议问题