我使用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
}
});
});