禁用未经授权的重定向到ASP.NET Core中的帐户/登录 [英] Disable Not Authorized Redirect to Account/Login in ASP.NET Core

查看:258
本文介绍了禁用未经授权的重定向到ASP.NET Core中的帐户/登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在共享库中有一组WebAPI服务.这些用于ASP.NET Core MVC网站和专用服务器中,仅托管WebAPI服务而没有MVC组件.

I have a set of WebAPI services in a shared library. These are used in an ASP.NET Core MVC Web Site and dedicated server only hosting the WebAPI Services without the MVC component.

MVC网站上的所有内容都可以正常运行,带有未授权的请求,我得到304重定向到登录页面(帐户/登录).但是,当我向WebAPI服务提出未经授权的请求时,在这种情况下,我会收到相同的304重定向到/Account/Login,我想返回Http 401未经授权的结果代码.我宁愿不在自定义AuthorizeAttribute中处理此问题,而宁愿在我的Startup类中的网站级别进行处理.

Everything works as expected on the MVC Web Site with Unauthorized Requests, I get the 304 redirect to the login page (Account/Login). However when I make an unauthorized request to the WebAPI services, I receive the same 304 redirect to /Account/Login in this case I would like to return the Http 401 Unauthorized result code. I would prefer to not handle this in a custom AuthorizeAttribute but would rather handle at the site level in my Startup class.

推荐答案

我怀疑您已经在MVC(视图)部分以及WebApi部分中注册了ASP.NET Core身份.

I suspect you have registered ASP.NET Core Identity with both your MVC (Views) Part as well as with your WebApi part.

您必须将其分开,并且CookieMiddleware(在.UseIdentity()调用中注册的一个)必须仅注册用于请求MVC页面,而不能用于WebAPI调用.

You must separate it and the CookieMiddleware (one registered inside .UseIdentity() call) must only be registered for request to your MVC pages, but not for your WebAPI calls.

您可以使用.MapMapWhen方法(请参阅文档).

You can use the .Map or MapWhen methods (see docs).

// For requests not going to WebAPI controllers
app.MapWhen(context => !context.Request.Path.StartsWithSegments("/api"), branch =>
{
    branch.UseIdentity();
});

这篇关于禁用未经授权的重定向到ASP.NET Core中的帐户/登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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