我在同一个控制器文件中有两种方法可以从JavaScript ajax接收数据。
第一个C#api控制器代码为
public class News
{
public int ID { get; set; }
public string Title { get; set; }
public string Intro { get; set; }
public string Story { get; set; }
public string Images { get; set; }
public DateTime DateModified { get; set; }
public DateTime DateCreated { get; set; }
}
public void InsertData([FromBody]News newsinfo)
{
conn.ConnectionString = mdc.ConnectonString;
cmd.Connection = conn;
if (newsinfo.ID > 0)
{
cmd.CommandText = "UPDATE [News] SET [Title] = N'" + newsinfo.Title + "', [Intro] = N'" + newsinfo.Intro + "', [Story] = N'" + newsinfo.Story + "', [Images] = N'" + newsinfo.Images + "', [DateModified] = @DateModified WHERE [ID] = " + newsinfo.ID;
cmd.Parameters.AddWithValue("@DateModified", DateTime.Now);
}
else
{
cmd.CommandText = "INSERT INTO [News] ([Title], [Intro], [Story], [Images], [DateCreated], [DateModified]) VALUES (N'" + newsinfo.Title + "', N'" + newsinfo.Intro + "', N'" + newsinfo.Story + "', '" + newsinfo.Images + "', @DateCreated, @DateModified)";
cmd.Parameters.AddWithValue("@DateCreated", DateTime.Now);
cmd.Parameters.AddWithValue("@DateModified", DateTime.Now);
}
conn.Open();
int send = cmd.ExecuteNonQuery();
conn.Close();
}
以上代码将从此JavaScript接收数据
function InsertData() {
var newsData = {
ID: editingID,
Title: $("#txbTitle").val().replace(/[\"]/gm, "\"").replace(/[\']/gm, "''"),
Intro: $("#txbIntro").val().replace(/[\"]/gm, "\"").replace(/[\']/gm, "''"),
Story: $(".ql-editor").html().replace(/[\"]/gm, "\"").replace(/[\']/gm, "''").replace(/http.\/\/[a-z:0-9]+/gm, "").replace(/\/Images.Temp\//gm, "/Images/News/"),
Images: imagesToUpload.replace(/Temp/gm, "News")
$.ajax({
url: "api/Database/InsertData",
method: "POST",
data: newsData,
success: function (result, status, xhr) {
if (imagesToUpload != "") {
var fileslist = {
filenames: ""
}
fileslist.filenames = imagesToUpload;
console.log(fileslist);
$.ajax({
url: "api/FileUpload/StoreImages",
method: "POST",
data: fileslist,
success: function (result, status, xhr) {
ViewState();
},
error: function (xhr, status, error) {
alert(error);
}
});
}
else if (imagesToUpload == "") {
ViewState();
}
},
error: function (xhr, status, error) {
alert(error);
}
});
}
第二个C#api控制器代码为
public class NewsId
{
public int[] id { get; set; }
}
[HttpPost]
public void DeleteData([FromBody]NewsId newsId)
{
conn.ConnectionString = mdc.ConnectonString;
cmd.Connection = conn;
if (newsId.id.Length > 0)
{
foreach (int id in newsId.id)
{
cmd.CommandText = "SELECT [Images] FROM [News] WHERE [Id] = " + id;
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
string images = "";
while (reader.Read())
{
images = reader[0].ToString();
}
conn.Close();
string[] files = Regex.Split(images, ";");
foreach (string file in files)
{
if (file != "")
{
string path = HttpContext.Current.Server.MapPath("~") + Regex.Replace(file, "/Images", "Images");
File.Delete(path); // /Images/Temp/
}
}
cmd.CommandText = "DELETE FROM [News] WHERE [Id] = " + id;
conn.Open();
int d = cmd.ExecuteNonQuery();
conn.Close();
}
}
}
它正在从JavaScript中接收数据
function DeletingNews(news_id) {
var newsId = {
id: news_id // news_id is Array
}
$.ajax({
url: "api/Database/DeleteData",
method: "POST",
data: newsId,
success: function (result, status, xhr) {
ViewState();
},
error: function (xhr, status, error) {
alert(error);
}
});
}
我不明白为什么第一代码不需要[HttpPost]而第二代码需要它,否则Ajax将返回
不允许使用405方法
两者现在都运行良好,但我只是不明白为什么有些需要[HttpPost],而另一些则不需要?
答案 0 :(得分:1)
默认情况下,API Controller提供了get,put,post和delete
默认情况下,让全部获取说IEnumerable GetAll()
默认情况下,Get是字符串Get(int id)
默认情况下,Post为空Post([FromBody]对象值)
默认情况下Put为空Put(int id,[FromBody] object value)
默认情况下删除为空Delete(int id)
仔细查看所使用的签名和返回类型 基于这些动作发生。
现在,如果要添加一个新动作,可以说“ Post”,那么您需要使用HttpPost属性装饰它,以便控制器了解要调用的动作
答案 1 :(得分:1)
因为我的C#API方法名称以与Http动词规则匹配的“删除”开头。
public void DeleteData([FromBody]NewsId newsId)
{
conn.ConnectionString = mdc.ConnectonString;
cmd.Connection = conn;
if (newsId.id.Length > 0)
我只需要像下面的代码一样将Ajax方法从“ POST”更改为“ DELETE”,即可解决此问题。
function DeletingNews(news_id) {
console.log(news_id);
var newsId = {
id: news_id
}
$.ajax({
url: "api/Database/DeleteData",
method: "DELETE", // <-- Changed from "POST"
data: newsId,
success: function (result, status, xhr) {
ViewState();
},
error: function (xhr, status, error) {
alert(error);
}
});
}
或者,另一种解决方案是将C#方法名称从“ Delete”更改为其他名称,并使用“ POST”保留Ajax方法,如以下代码所示。
public void RemoveData([FromBody]NewsId newsId) // <-- Change method's name from "DeleteData" to "RemoveData"
{
conn.ConnectionString = mdc.ConnectonString;
cmd.Connection = conn;
if (newsId.id.Length > 0)
function DeletingNews(news_id) {
console.log(news_id);
var newsId = {
id: news_id
}
$.ajax({
url: "api/Database/RemoveData", // <-- Change action url from "DeleteData" to "RemoveData"
method: "POST",
data: newsId,
success: function (result, status, xhr) {
ViewState();
},
error: function (xhr, status, error) {
alert(error);
}
});
}