解决方法
您可以使用此简单而有效的机制使用自定义ActionFilter属性:
public class BasicAuthenticationAttribute : ActionFilterAttribute { 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 override void OnActionExecuting(ActionExecutingContext 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 (user.Name == Username && user.Pass == Password) return; } filterContext.HttpContext.Response.AddHeader("WWW-Authenticate",String.Format("Basic realm=\"{0}\"",BasicRealm ?? "Ryadel")); /// thanks to eismanpat for this line: http://www.ryadel.com/en/http-basic-authentication-asp-net-mvc-using-custom-actionfilter/#comment-2507605761 filterContext.Result = new HttpUnauthorizedResult(); } }
它可以用于将基本认证置于整个控制器中:
[BasicAuthenticationAttribute("your-username","your-password",BasicRealm = "your-realm")] public class HomeController : BaseController { ... }
或具体ActionResult:
public class HomeController : BaseController { [BasicAuthenticationAttribute("your-username",BasicRealm = "your-realm")] public ActionResult Index() { ... } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。