[英]MVC 5 Custom ActionFilter not working
I'm trying to implement basic authentication to a service using this question as a template. 我正在尝试使用此问题作为模板来实现对服务的基本身份验证。
For some reason the action filter is never applied to my controllers and I have no idea why. 由于某种原因,动作过滤器从未应用于我的控制器,我也不知道为什么。
My controller: 我的控制器:
[BasicAuthenticationManager("username", "password")]
public class DataController : ApiController
{
private DataEntities db = new DataEntities();
// GET: api/Data
//[BasicAuthenticationManager]
public IHttpActionResult GetvwData()
{
return Json(db.vwData);
}
}
My filter: 我的过滤器:
public class BasicAuthenticationManager : ActionFilterAttribute
{
protected string userName { get; set; }
protected string password { get; set; }
public BasicAuthenticationManager(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 credentials = ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(auth.Substring(6))).Split(':');
var user = new { Name = credentials[0], Pass = credentials[1] };
if (user.Name == userName && user.Pass == password) return;
}
filterContext.Result = new HttpUnauthorizedResult();
}
}
I don't get an error messaage and the filter is recogniced by code autocompletion. 我没有收到错误消息,并且代码自动补全功能可以识别过滤器。
Inherit from System.Web.Http.AuthorizeAttribute instead of ActionFilterAttribute. 从System.Web.Http.AuthorizeAttribute继承,而不是从ActionFilterAttribute继承。 You can override the IsAuthorized method.
您可以重写IsAuthorized方法。
protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
{
//Auth logic
//return whether user is authorized or not.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.