在Windows窗体应用程序上调用Web API时出错

时间:2016-07-08 06:31:44

标签: c# winforms asp.net-web-api

  

首先我添加了名为产品的模型类,如下所示

public class Product
{
    public int Id { get; set; }
    public string Names { get; set; }
    public string Category { get; set; }
    public string Price { get; set; }
}
  

然后我添加 Productcontroller ,如下所示

    public List<Product> GetAllProducts()
    {
        con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connect"].ConnectionString);
        List<Product> product = new List<Product>();
        cmd = new SqlCommand("select * from AddName", con);

        con.Open();
        dr = cmd.ExecuteReader();
        while (dr.Read())
        {

            product.Add(
                new Product
                {
                    Id=int.Parse(dr["Id"].ToString()),
                    Names = dr["Name"].ToString(),
                    Category = dr["LName"].ToString(),
                    Price = dr["Company"].ToString()
                }
                );

        }
        con.Close();
        return product;
    }
    public string SaveData(Product Pr)
    {
        con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connect"].ConnectionString);
        cmd = new SqlCommand("insertData", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@Name",Pr.Names);
        cmd.Parameters.AddWithValue("@LName", Pr.Category);
        cmd.Parameters.AddWithValue("@Company", Pr.Price);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        return "Data Save Successfully";
    }
    public string msg()
    {
        return "this is A Msg Method";
    }
    public string DeleteData(int Id)
    {
        con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connect"].ConnectionString);
        cmd = new SqlCommand("delete from AddName where Id=@Id", con);
        cmd.Parameters.AddWithValue("@Id", Id);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        return "Data deleted Successfully";
    }
    public List<Product> GetProduct(int id)
    {
        con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connect"].ConnectionString);
        List<Product> product = new List<Product>();
        cmd = new SqlCommand("select * from AddName where Id=@Id",con);
        cmd.Parameters.AddWithValue("@Id", id);
        con.Open();
        dr = cmd.ExecuteReader();
        if(dr.Read())
        {
            product.Add(
                new Product { 
                Names=dr["Name"].ToString(),
            Category=dr["LName"].ToString(),
            Price=dr["Company"].ToString()
                }
                );
        }
        con.Close();


        return product;
    }
  

我已经在html表单上测试了web API,并且它通过ajax jquery工作正常。但是在调用Windows表单应用程序时给出错误,我的意思是这是给出html源而不是返回值   enter image description here

0 个答案:

没有答案