Override ASP.NET forms authentication for a single page

前端 未结 3 2071
长情又很酷
长情又很酷 2021-02-10 00:16

In our ASP.NET MVC application, we automatically redirect users to a log-on page via the section of when they

3条回答
  •  我寻月下人不归
    2021-02-10 00:41

    The following solution works, although I'm not at all sure it's optimal:

    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();
        }
    }
    

    You can then return the above result instead of an HttpUnauthorizedResult to generate the required 401 code. This feels quite klugy to me, however.

提交回复
热议问题