获取AuthorizeFilter中的api控制器构造函数值

时间:2014-01-16 22:04:54

标签: asp.net-web-api authorize-attribute asp.net-web-api2

当用户通过身份验证时,我想通过告诉他您没有权限403来阻止他更新/删除/读取从其他帐户创建的数据!

获取ISchoolyearService实例以调用其HasUserPermission()方法的最佳方法是什么?

我知道我可以在这里新建一下SchoolyearService,但这会在我的应用程序中使用IoContainer来解决这个问题。

public class UserActionsSchoolyearAuthorizationFilter : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (actionContext != null)
        {
            bool canUserExecuteAction = false;
            if (actionContext.Request.Method == HttpMethod.Put)
            {
                int schoolyearId = Convert.ToInt32(actionContext.Request.GetRouteData().Values["Id"]);
                int userId = actionContext.Request.Content.ReadAsAsync<SchoolyearEditRequest>().Result.Schoolyear.UserId;
                //var schoolyearService = actionContext.ControllerContext.Controller.GetContstructorParameterServiceInstance();
                //canUserExecuteAction = schoolyearService.HasUserPermission(userId, schoolyearId);
                if (canUserExecuteAction)
                {
                    base.OnAuthorization(actionContext);
                }
                else
                {
                    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
                }

            }
            // Removed for brevity

    private readonly ISchoolyearService _service;
            public SchoolyearController(ISchoolyearService service)
            {
                _service = service;
            }

2 个答案:

答案 0 :(得分:0)

如果你在SchoolyearController上公开_service参数,你可以在OnAuthorization方法中尝试这样的事情:

var schoolyearController = actionContext.ControllerContext.Controller as SchoolyearController;
canUserExecuteAction = schoolyearController._service.HasUserPermission(userId, schoolyearId);

答案 1 :(得分:0)

好的,最后我发现了如何从当前请求中获取ISchoolyearService:

从DependencyScope获取已注册的服务!

现在这个属性应该直接放在控制器上。由于http动词上的if / else,我不需要把它放在动作上。

bool canUserExecuteAction = false;
if (actionContext.Request.Method == HttpMethod.Put)
{
    int targetId = Convert.ToInt32(actionContext.Request.GetRouteData().Values["Id"]);
    int userId = actionContext.Request.Content.ReadAsAsync<SchoolyearEditRequest>().Result.Schoolyear.UserId;
    var requstScope = actionContext.ControllerContext.Request.GetDependencyScope();
    var service = requstScope.GetService(typeof(ISchoolyearService)) as ISchoolyearService;
    canUserExecuteAction = service.HasUserPermission(userId, targetId);

    if (canUserExecuteAction)
    {
        base.OnAuthorization(actionContext); 
    }
    else
    {
        actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
    }
}