覆盖单个页面的ASP.NET表单身份验证

Ben*_*ack 5 asp.net authentication asp.net-mvc forms-authentication

在我们的ASP.NET MVC应用程序,我们会自动通过将用户重定向到一个登录页面<authentication>的部分<system.web>,当他们试图访问授权,仅页面.问题是应用程序中间的一个操作(设计为由工具使用)需要在错误访问时返回直接的HTTP 401响应.如何在没有针对此特定操作的重定向的情况下返回真正的HTTP 401代码?

Ben*_*ack 6

以下解决方案有效,但我不确定它是否是最佳的:

public class HttpAuthenticationRequiredResult : ActionResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        var response = context.HttpContext.Response;
        response.StatusCode = 401;
        response.AddHeader("WWW-Authenticate", "Basic realm=\"whatever\"");
        response.Flush();
        response.Close();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以返回上述结果而不是HttpUnauthorizedResult来生成所需的401代码.然而,这对我来说非常麻烦.