如何将数据(Json格式)发布到webservice方法,该方法是C#中Json格式的返回响应

本文关键字:格式 方法 Json 响应 返回 数据 webservice | 更新日期: 2023-09-27 18:28:31

以下是web服务方法

    [WebMethod]
    public void GetEmployees(int pageNumber, int pageSize)
    {
        List<Employee> listEmployees = new List<Employee>();
        string cs =  ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
        using (SqlConnection con = new SqlConnection(cs))
        {
            SqlCommand cmd = new SqlCommand("spGetEmployees", con);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter()
            {
                ParameterName = "@PageNumber",
                Value = pageNumber
            });
            cmd.Parameters.Add(new SqlParameter()
            {
                ParameterName = "@PageSize",
                Value = pageSize
            });
            con.Open();
            SqlDataReader rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                Employee employee = new Employee();
                employee.ID = Convert.ToInt32(rdr["Id"]);
                employee.Name = rdr["Name"].ToString();
                employee.Gender = rdr["Gender"].ToString();
                employee.Salary = Convert.ToInt32(rdr["Salary"]);
                listEmployees.Add(employee);
            }
        }
        JavaScriptSerializer js = new JavaScriptSerializer();
        Context.Response.Write(js.Serialize(listEmployees));
    }
}

现在我需要使用控制台或web表单来使用此服务方法

如何将数据(Json格式)发布到webservice方法,该方法是C#中Json格式的返回响应

您可以使用此代码将POST发送到您的web服务(TR请求类,T响应级)

protected T PostAsync<T, TR>(string serviceUrl, TR request)
{
    using (var client = new HttpClient())
    {
        var baseUrl = "";
        client.BaseAddress = new Uri(baseUrl);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var response = client.PostAsJsonAsync(serviceUrl, request).Result;
        if (response.IsSuccessStatusCode)
        {
            var responseString = response.Content.ReadAsStringAsync().Result;
            return JsonConvert.DeserializeObject<T>(responseString);
        }
    }
    return default(T);
}

如果你想让GET请求

protected T GetAsync<T>(string serviceUrl)
{
    using (var client = new HttpClient())
    {
        var baseUrl = "";
        client.BaseAddress = new Uri(baseUrl);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var response = client.GetAsync(serviceUrl).Result;
        if (response.IsSuccessStatusCode)
        {
            var responseString = response.Content.ReadAsStringAsync().Result;
            return JsonConvert.DeserializeObject<T>(responseString);
        }
    }
    return default(T);
}

使用静态方法返回Json字符串First Like Below

[WebMethod]
    public static string GetEmployees(int pageNumber, int pageSize)
    {
        List<Employee> listEmployees = new List<Employee>();
        string cs =  ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
        using (SqlConnection con = new SqlConnection(cs))
        {
            SqlCommand cmd = new SqlCommand("spGetEmployees", con);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter()
            {
                ParameterName = "@PageNumber",
                Value = pageNumber
            });
            cmd.Parameters.Add(new SqlParameter()
            {
                ParameterName = "@PageSize",
                Value = pageSize
            });
            con.Open();
            SqlDataReader rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                Employee employee = new Employee();
                employee.ID = Convert.ToInt32(rdr["Id"]);
                employee.Name = rdr["Name"].ToString();
                employee.Gender = rdr["Gender"].ToString();
                employee.Salary = Convert.ToInt32(rdr["Salary"]);
                listEmployees.Add(employee);
            }
        }
        JavaScriptSerializer js = new JavaScriptSerializer();
        return js.Serialize(listEmployees);
    }
}

在下面的Ajax网页上调用此

  $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "YourPageName.aspx/GetEmployees",
                data: { pageNumber: 1, pageSize: 10 },
                dataType: "json",
                success: function (data) {
                    var jsondata = JSON.parse(data.d);
                    for (var i = 0; i < jsondata.length; i++) {
                       //DO Your Work
                    }

                },
                error: function (result) {

                }
            });