我正在web api項目中工作,其中我必須編寫刪除帳戶的方法。 我已經創建了一個名爲RemoveAccount的控制器,我已經寫了我的Delete帳戶方法。 以下是代碼。如何使用ajax調用在REST中調用@DELETE Web服務?
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; }
}
我創建了一個單獨的測試項目來測試這個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和我得到「內部服務器錯誤」僅適用於這種方法,休息所有工作都很好。
我哪裏錯了?
你能提供一些關於這個錯誤的細節嗎?在瀏覽器或Fiddler中使用開發工具可以給我們更多的細節 – Novakov