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

时间:2015-12-29 09:31:40

标签: c# json webservices-client

这是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));
    }
}

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

2 个答案:

答案 0 :(得分:1)

您可以将此代码用于POST到您的网络服务(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);
}

答案 1 :(得分:0)

使用静态方法返回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) {


                }
            });