我有以下 asp.net web api 方法来删除文件:
[Authorize]
[HttpPost]
public IHttpActionResult Delete(int id)
{
var uploadedFile = unitOfWork.FileRepository.Get(id);
if (uploadedFile == null)
return NotFound();
if (uploadedFile.CreatedBy != User.Identity.GetUserId())
return Unauthorized();
unitOfWork.FileRepository.Remove(uploadedFile);
unitOfWork.Complete();
return Ok();
}
如果尝试删除文件的用户并未创建该文件,我想返回一个 unauthorized
结果。我有以下 ajax 来处理调用,但在测试时我总是得到响应 200,所以 fail 函数永远不会在我的 ajax 函数中被调用?
我已经用断点调试了 web api 方法,它显然触发了 Unauthorized 方法 - return Unauthorized();
那么为什么当我在 firefox 控制台中查看时它返回状态 200:
POST http://localhost:65179/api/file/2 200 OK 29ms
当我在控制台中检查响应 header 时,它显示以下内容:
X-Responded-JSON {"status":401,"headers":{"location":"http:\/\/localhost:65179\/Account\/Login?ReturnUrl=%2Fapi%2Ffile%2F94"}}
所以我不知道为什么没有调用 fail 函数?我认为它正在重定向到登录页面,因此状态返回为 200。那么我该如何抑制重定向?
function () {
$.ajax({
url: "api/file/2",
method: "POST"
})
.done(function () {
alert("File has been deleted.");
})
.fail(function ( jqXHR) {
alert("Unable to delete file");
});
});
*** 更新 ****
我发现以下博客文章是一个潜在的解决方案,但它仅在您的项目仅为 web api 时才有效。
我的项目是 MVC 5 和 web api 2 的组合,所以我修改了它并将代码添加到 startup.auth.cs 如下,但我不得不注释掉 OnValidateIdentity
位以便将 OnApplyRedirect
添加到 cookie 选项。
public void ConfigureAuth(IAppBuilder app)
{
var cookieOptions = new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
//OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
// validateInterval: TimeSpan.FromMinutes(30),
// regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
OnApplyRedirect = ctx =>
{
if (!IsApiRequest(ctx.Request))
{
ctx.Response.Redirect(ctx.RedirectUri);
}
}
}
};
app.UseCookieAuthentication(cookieOptions);
}
private static bool IsApiRequest(IOwinRequest request)
{
string apiPath = VirtualPathUtility.ToAbsolute("~/api/");
return request.Uri.LocalPath.StartsWith(apiPath);
}
最佳答案
正确的方法是使用错误回调
$.ajax({
url: "api/file/2",
method: "POST"
})
.success(function () {
alert("File has been deleted.");
})
.error(function (xhr, textStatus, errorThrown) {
alert("Unable to delete file");
});
查看文档 here
关于c# - ASP.Net Web API 和 JQuery Ajax - 如何处理 401 未经授权的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41715108/