1

当用户通过身份验证时,我想防止他更新/删除/读取从其他帐户创建的数据......通过告诉他您没有权限 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;
            }
4

2 回答 2

0

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

var schoolyearController = actionContext.ControllerContext.Controller as SchoolyearController;
canUserExecuteAction = schoolyearController._service.HasUserPermission(userId, schoolyearId);
于 2014-01-17T08:33:23.987 回答
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);
    }
}
于 2014-01-17T10:11:43.993 回答