Suppress redirect on API URLs in ASP.NET Core

前端 未结 3 1221
名媛妹妹
名媛妹妹 2020-12-09 17:08

I have an ASP.NET Core site that uses cookie authentication for most pages. For those pages, the default server response of providing a 302 redirect for an unauthorized clie

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-09 17:41

    Other simple way

     .AddCookie(options =>
                {
                    options.AccessDeniedPath = "/Home/401";
                    options.Events = new CookieAuthenticationEvents
                    {
                        OnRedirectToAccessDenied = context => 
                        {
                            if (context.Request.Path.StartsWithSegments("/api"))
                            {
                                context.Response.StatusCode = (int)(HttpStatusCode.Unauthorized);
                            }
                            return Task.CompletedTask;
                        },
                    };
                })
    

提交回复
热议问题