【问题标题】:How Do I post JSON Data With Ajax Using C#如何使用 C# 使用 Ajax 发布 JSON 数据
【发布时间】:2016-04-06 06:54:55
【问题描述】:

大家好,我正在尝试将 JSON 发布到我可以使用 AJAX 和 cURL 执行的 API。

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

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

但是,当我尝试从 C# 发布时:

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" } 发送数据,我认为我的控制器无法使用:

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";
}

【问题讨论】:

标签: c# .net json ajax post


【解决方案1】:

由于您在尝试以 FormData 的形式访问它时将 json 作为请求负载传递。无需使用 [FromBody]

public string Post(FormDataCollection formValues)

【讨论】:

    【解决方案2】:

    您不应使用 [FormBody] 也不应使用 FormDataCollection。您应该创建一个具有 Firstname Lastname 和 Email 作为属性的模型。

    你的方法如下所示:

    public string Post(PersonInformation personInformation)
    

    【讨论】:

      猜你喜欢
      • 2021-08-28
      • 2011-02-23
      • 1970-01-01
      • 2013-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-17
      • 2015-05-05
      相关资源
      最近更新 更多