如何使用C#使用Ajax发布JSON数据

时间:2016-04-06 06:54:55

标签: c# .net json ajax post

大家好我想把JSON发布到API,我可以用AJAX和cURL。

C#.net应用程序中的代码可以处理cURL代码并将其写入SQL:

curl "http://localhost:38194/API/inbound" --data "FirstName=test4&LastName=test&Email=donot@mail.com"

但是,当我尝试使用以下命令从C#进行POST时

using (var client = new HttpClient())
{
    var request = new 
    {
        FirstName = reader[1],
        LastName = reader[2],
        Email = reader[3]
    };

    var response = client.PostAsync("http://localhost:38194/API/inbound", 
        new StringContent(JsonConvert.SerializeObject(request).ToString(), Encoding.UTF8, "application/json")).Result;

    if (response.IsSuccessStatusCode)
    {
        //Do something
    }
}

它将数据发送为request = { FirstName = "Tom", LastName = "Buckle", Email = "sdjsa@kjsdfhs.com" },我认为我的Controller无法使用:

public string Post([FromBody] FormDataCollection formValues)   

我已经搜索并花费了数小时,并怀疑我发送POST的格式不适用于我的API控制器FormDataCollection。我必须承认,我对这些东西并不了解,并通过反复试验来了解更多。可能不优雅,但这是我的API控制器代码,适用于cURL。

public string Post([FromBody] FormDataCollection formValues)
{
    string first_name = null, last_name = null, email = null;

    string connStr = ConfigurationManager.ConnectionStrings["inboundapplicant"].ConnectionString;
    using (SqlConnection connection = new SqlConnection(connStr))
    {
        using (SqlCommand command = new SqlCommand())
        {

            if (!string.IsNullOrWhiteSpace(formValues.Get("FirstName")))
            {
                first_name = formValues.Get("FirstName");
            }
            if (!string.IsNullOrWhiteSpace(formValues.Get("LastName")))
            {
                last_name = formValues.Get("LastName");
            }
            if (!string.IsNullOrWhiteSpace(formValues.Get("Email")))
            {
                email = formValues.Get("Email");
            }

            command.Connection = connection;
            command.CommandType = CommandType.Text;
            command.CommandText = "INSERT into [dbo].[Leads] (FirstName, LastName, Email) VALUES (@first_name, @last_name, @email)";

            command.Parameters.AddWithValue("@first_name", first_name == null ? (object)DBNull.Value : first_name);
            command.Parameters.AddWithValue("@last_name", last_name == null ? (object)DBNull.Value : last_name);
            command.Parameters.AddWithValue("@email", email == null ? (object)DBNull.Value : email);


            try
            {
                connection.Open();
                int recordsAffected = command.ExecuteNonQuery();
            }
            catch (SqlException)
            {
                throw;
            }
            finally
            {
                connection.Close();
            }
        }
    }

    return "success";
}

2 个答案:

答案 0 :(得分:0)

因为当您尝试将其作为FormData访问时,您将json作为请求有效负载传递。无需使用[FromBody]

public string Post(FormDataCollection formValues)

答案 1 :(得分:0)

您不应该使用[FormBody]并且不要使用FormDataCollection。您应该使用名字姓氏和电子邮件作为属性创建模型。

您的方法如下所示:

public string Post(PersonInformation personInformation)