禁止在ASP.NET Core中的API URL上重定向 [英] Suppress redirect on API URLs in ASP.NET Core

查看:248
本文介绍了禁止在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 Core2.代码适用于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上重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆