c# - ASP.Net Web API 和 JQuery Ajax - 如何处理 401 未经授权的结果

标签 c# jquery asp.net ajax asp.net-web-api2

我有以下 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 时才有效。

https://brockallen.com/2013/10/27/using-cookie-authentication-middleware-with-web-api-and-401-response-codes/

我的项目是 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/

相关文章:

c# - 在 ASP.NET Core 中使用 Ajax 更新下拉列表

asp.net - Ajax htmlEditorExtender - 无法识别的元素清理程序

c# - 如何在应用程序中使用引用同一 dll 的不同版本的两个 dll?

jquery - 是否有任何 jQuery 教程演示了接受选择器语法的创作插件?

javascript - 在动态添加的文本框中输入文本时启用按钮

jquery - 在点击事件上滑动 slider (Slick Slider)

c# - 在 GridView 中缩放图像

c# - 嵌入式 Mysql (libmysql.dll) 和 C# & Asp.Net

c# - 修改异步不工作

c# - ContinueWith 主线程上的任务