【发布时间】: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";
}
【问题讨论】:
-
bing.com/search?q=Issue+Post+JSON+C%23+webapi 应该会给你一些答案...