[英]How to to invoke an @DELETE web service in REST using ajax call?
我正在研究Web api項目,其中我必須編寫刪除帳戶的方法。 我創建了一個名為RemoveAccount的控制器,並在其中編寫了我的Delete account方法。 以下是代碼。
public RemoveAccountRes Delete(RemoveAccountModel objRemove, string function = "")
{
RemoveAccountRes objModel = new RemoveAccountRes();
if (ModelState.IsValid)
{
User user = null;
try
{
user = UserHelper.GetLoggedInUser(Convert.ToString(user.UserGuid));
if (user == null || objRemove.User == null)
{
objModel.ErrorMessage = "User Not Valid";
objModel.ErrorCode = 403;
objModel.Success = false;
return objModel;
}
if (function == "delete")
{
UserRepository.Delete(objRemove.User.UserId);
UserHelper.LogOutUser();
objModel.ErrorMessage = "Account is Deleted";
objModel.ErrorCode = 200;
objModel.UserGuid = Convert.ToString(user.UserGuid);
objModel.Success = true;
}
}
catch (Exception ex)
{
objModel.ErrorMessage = "Unidentified Error";
objModel.ErrorCode = 500;
objModel.UserGuid = Convert.ToString(user.UserGuid);
}
return objModel;
}
else
{
objModel.ErrorMessage = "Invalid/Incomplete requests";
objModel.ErrorCode = 400;
return objModel;
}
}
上述方法的模型為:
public class RemoveAccountModel
{
public User User { get; set; }
}
public class RemoveAccountRes
{
public int ErrorCode { get; set; }
public string ErrorMessage { get; set; }
public int UserId { get; set; }
public string UserGuid { get; set; }
public bool Success { get; set; }
}
我創建了一個單獨的Test項目來測試此api方法。 以下是單擊刪除按鈕后調用的ajax調用:
$(document).ready(function () {
$("#btnDelete").click(function () {
alert("Hello");
var request = $.ajax({
url: "http://localhost:13979/api/RemoveAccount?function='delete'",
type: "DELETE",
dataType: "json"
});
request.done(function (msg) {
alert("Request success: " + msg);
$("#divResponse").empty().append("<span>" + JSON.stringify(msg) + "</span>");
//console.log(JSON.stringify(msg));
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
$("#divResponse").empty().append("<span>" + JSON.stringify(textStatus) + "</span>");
//console.log(JSON.stringify(textStatus));
});
});
});
當我嘗試調試時,我發現它沒有調用該URL,並且僅為此方法獲取“內部服務器錯誤”,其余所有工作正常。
我要去哪里錯了?
您已經有了參數function=delete
,如果HTTP請求的類型為DELETE
真的很重要嗎,我建議將其更改為POST
來自jQuery docs :
發出請求的類型(“ POST”或“ GET”),默認為“ GET”。 注意:其他HTTP請求方法(例如PUT和DELETE)也可以在此處使用,但並非所有瀏覽器都支持。
另一件事...您將此映射正確嗎?
http://localhost:13979/api/RemoveAccount
正在調用一個名為Delete
的函數-如果您在路由代碼中處理該函數,那就很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.