从ActionFilter中止/取消操作的最佳方法
我有这个ActionFilter
,并且假设立即结束连接并返回401 Unauthroized:
public class SignInRequired : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// User is verified, continue executing action
if (Acme.Web.CurrentUser != null)
{
return;
}
// End response with 401 Unauthorized
var response = HttpContext.Current.Response;
response.StatusCode = (int)HttpStatusCode.Unauthorized;
response.End();
// Prevent the action from actually being executed
filterContext.Result = new EmptyResult();
}
}
Run Code Online (Sandbox Code Playgroud)
我学会了如何通过在这里设置'context.Result = new EmptyResult()`来取消执行操作,但我不确定这是否是刷新响应和关闭连接的最佳方法.
我正在开发支持表单身份验证的ASP.NET MVC5项目.Project目前处于测试阶段,并在Azure上进行在线托管,但项目所有者希望禁用对该站点的所有公共访问(因为站点的某些部分根本不需要用户进行身份验证).
在此测试阶段,我们决定从此链接实施基本HTTP身份验证.我已经更改了代码,因此它更符合我的需求:
public class BasicAuthenticationAttribute : FilterAttribute, IAuthorizationFilter
{
public string BasicRealm { get; set; }
protected string Username { get; set; }
protected string Password { get; set; }
public BasicAuthenticationAttribute(string username, string password)
{
this.Username = username;
this.Password = password;
}
public void OnAuthorization (AuthorizationContext filterContext)
{
var req = filterContext.HttpContext.Request;
var auth = req.Headers["Authorization"];
if (!String.IsNullOrEmpty(auth))
{
var cred = System.Text.ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(auth.Substring(6))).Split(':');
var user = new { Name = cred[0], Pass = cred[1] };
if …
Run Code Online (Sandbox Code Playgroud) c# asp.net asp.net-mvc basic-authentication antiforgerytoken
我有一个 ASP MVC 应用程序,它使用它自己的自定义身份验证机制。但是,我需要使用基本身份验证来保护一个控制器中只有一个操作。
这个想法是当这个特定操作的 URL 被点击时,浏览器会弹出基本身份验证对话框,然后我需要在操作本身中输入用户名和密码。
有什么建议?