c# - 使 Web API 身份验证返回 401 而不是重定向到登录页面

标签 c# asp.net asp.net-mvc authentication asp.net-web-api

我在 Web MVC 中有带有 OWIN 身份验证的 Web API。 我正在使用 <authentication>在我的 Web MVC 的 Web.Config 中,因此它重定向到登录页面。

<authentication mode="Forms">
    <forms name="WEB.AUTH" loginUrl="~/login" domain="" protection="All" 
    timeout="43200" path="/" requireSSL="false" slidingExpiration="true" />
</authentication>

我正在使用 [System.Web.Http.Authorize]属性来授权我的 Web API。但不知何故,由于上述配置,API 重定向到登录页面与我的 MVC 应用程序相同。

我想做的是继续为 Web MVC 重定向功能,但为 Web API 返回 401。我怎样才能做到这一点?我应该为 Web API 创建自定义授权属性吗?

--编辑--

我从这篇文章中找到了答案SuppressDefaultHostAuthentication in WebApi.Owin also suppressing authentication outside webapi

所以我只是在我的 Startup.cs 中添加了几行.我为所有 Controller 配置了“api”前缀路由。

HttpConfiguration config = new HttpConfiguration();
//..some OWIN configuration
app.Map("/api", inner =>
{
  inner.UseWebApi(config);
});

确保你输入 app.Map()在 Web Api 配置行之后。否则,它会给 MVC 应用程序带来错误。

最佳答案

在 .NET Core 中我是这样解决的,Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.Cookie.SameSite = SameSiteMode.Strict;
                options.Cookie.Name = "AuthCookie";
                options.Events.OnRedirectToAccessDenied = UnAuthorizedResponse;
                options.Events.OnRedirectToLogin = UnAuthorizedResponse;
            })
    ....
    }

    internal static Task UnAuthorizedResponse(RedirectContext<CookieAuthenticationOptions> context)
    {
        context.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
        return Task.CompletedTask;
    }

关于c# - 使 Web API 身份验证返回 401 而不是重定向到登录页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34880817/

相关文章:

c# - ASP.NET MVC ViewModel 属性为空

wpf - DataAnnotations 元数据类型不工作

c# - 在 .NET/C# 中从数据库检索的子字符串值

c# - 为什么 IoC 会影响 Controller 的创建以及如何解决这个问题?

javascript - 动态生成一个选择类型,其中包含单击添加按钮时指定的选项

c# - ASP.NET HttpPost 方法。无法正常接收数据

asp.net-mvc - 需要时在 CQRS 中提供同步行为?

asp.net-mvc - 向 Flash、JavaScript 等发送自定义 HTTP 错误信息

c# - 在 ASP.NET 中使用委托(delegate)来处理异步操作

c# - 如何避免在递归算法中达到线程池的最大值?