本文介绍了在 ASP.NET Core 中禁止对 API URL 进行重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ASP.NET Core 站点,该站点对大多数页面使用 cookie 身份验证.对于这些页面,为未经授权的客户端提供 302 重定向的默认服务器响应是可取的.但是,该站点也接受 API 请求;他们使用 API 密钥,不使用 cookie.

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 client is desirable. However, the site also accepts API requests; they use API keys and have no use for cookies.

理想情况下,我想完全关闭 API URL 的 cookie 处理,但至少,我需要确保如果 API 客户端未经授权,服务器不会响应 302 重定向.

Ideally, I'd like to turn off cookie processing for the API URLs altogether, but minimally, I need to ensure that if an API client is unauthorized, the server doesn't respond with a 302 redirect.

推荐答案

使用仅当路径不是 API 时才使用默认行为的重定向事件处理程序替换重定向事件处理程序.在 Startup.ConfigureServices 中,添加:

Replace the redirect event handler with one that uses the default behavior only if the path is not an API. In Startup.ConfigureServices, add this:

services.ConfigureApplicationCookie(options => {
    options.Events.OnRedirectToAccessDenied = ReplaceRedirector(HttpStatusCode.Forbidden, options.Events.OnRedirectToAccessDenied);
    options.Events.OnRedirectToLogin = ReplaceRedirector(HttpStatusCode.Unauthorized, options.Events.OnRedirectToLogin);
});

使用此辅助方法替换重定向方法:

Use this helper method to replace the redirect methods:

static Func<RedirectContext<CookieAuthenticationOptions>, Task> ReplaceRedirector(HttpStatusCode statusCode, Func<RedirectContext<CookieAuthenticationOptions>, Task> existingRedirector) =>
    context => {
        if (context.Request.Path.StartsWithSegments("/api")) {
            context.Response.StatusCode = (int)statusCode;
            return Task.CompletedTask;
        }
        return existingRedirector(context);
    };

有了这个,API 控制器方法可以调用 Unauthorized()Forbid() 而不会导致重定向.

With this in place, the API controller methods can call Unauthorized() and Forbid() without causing redirects.

更新:以上适用于 ASP.NET Core 2.ASP.NET Core 1 的代码 是不同的.

Update: The above is for ASP.NET Core 2. The code for ASP.NET Core 1 is different.

这篇关于在 ASP.NET Core 中禁止对 API URL 进行重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 15:06