使用自定义AuthorizeAttribute时获取null值而不是Id

时间:2016-08-11 05:09:35

标签: asp.net-mvc asp.net-mvc-5 model-binding

我使用ajax调用调用此操作方法:

[AuthorizeCheckCreator]
[HttpPost]
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
public ActionResult Delete(Guid id)
{
    // code....
    return Content("ok");
}

我创建了一个自定义AuthorizeAttribute来检查用户的权限(我想确定用户是否是该记录的所有者):

public class AuthorizeCheckCreatorAttribute : AuthorizeAttribute
{
    public IRequest RequestService { get; set; }
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        RequestCheckUserViewModel request;
        if (httpContext.Request.IsAjaxRequest())
        {
            var ajaxId = JsonConvert.DeserializeObject<GetId>(System.Text.Encoding.UTF8
                                    .GetString(httpContext.Request.BinaryRead(httpContext.Request.ContentLength)));
            var currentId = ajaxId.Id;
            var isAuthorized = base.AuthorizeCore(httpContext);
            if (!isAuthorized) return false;
            requestBank = RequestService.GetUserId(Guid.Parse(currentId));
        }
        else
        {
            var rd = httpContext.Request.RequestContext.RouteData;
            var currentId = rd.GetRequiredString("id");
            var isAuthorized = base.AuthorizeCore(httpContext);
            if (!isAuthorized) return false;
            requestBank = RequestService.GetUserId(Guid.Parse(currentId));
        }

        var result = httpContext.User.Identity.GetUserId<int>() == request.UserId ||
                     httpContext.User.IsInRole("Admin") ||
                     httpContext.User.IsInRole("BankResponsible") ||
                     httpContext.User.IsInRole("BankManager");
        return result;
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        // handling the unauthorized requests
    }
}

public class GetId
{
    public string Id { get; set; }
}

有了这段代码,我总是得到id参数的空值。我确信客户端代码工作正常,因为当我从[AuthorizeCheckCreator]操作方法中删除Delete时,我得到id的值。 有什么想法吗?

更新
Ajax电话:

$('.btnDelete').click(function (event) {
    event.preventDefault();
    var btn = $(this);
    var requestId = btn.data("id");
    $.ajax({
        type: "POST",
        url: '/bank/request/delete',
        data: JSON.stringify({ id: requestId }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        complete: function (xhr, status) {
            // code
        }
    });
});

0 个答案:

没有答案