2012-03-01 70 views
27

内的动作参数值我有我从jQuery的发布到一个动作:获得一个动作过滤器

[HttpPost] 
public void UpdateGroupName(int groupId, string name) 
{ 
    authorisationRepository.UpdateGroupName(groupId, name); 
} 

也能正常工作与groupIdname。我还有其他一些小组操作,因此我想使用授权属性来确保执行更改的人员有权进行更改。

我已经有一个AuthorizationAttribute,通过访问filterContext.HttpContext.Request.Params["groupId"]在GET请求上成功检索groupId,但是当谈到POST时,它不起作用。 Request.Form是空的,Request.Params也是空的。

下面是我在我的授权属性代码:

public int groupId { get; set; } 

protected override bool AuthorizeCore(HttpContextBase httpContext) 
{ 
    username = httpContext.User.Identity.Name.Split('\\').Last(); 

    // awesome permissions checking goes here... 

    return authorized; 
} 

public override void OnAuthorization(AuthorizationContext filterContext) 
{ 
    groupId = int.Parse(filterContext.HttpContext.Request.Params["groupId"]); // this line throws an exception 
    base.OnAuthorization(filterContext); 
} 

我已经看过这个answer但我Form属性为空:(

更新,以显示jQuery的岗位:

var serverComm = { 
    post: function (url, data) { 
     return $.ajax({ 
      url: url, 
      type: 'POST', 
      contentType: 'application/json; charset=utf-8', 
      data: JSON.stringify(data) 
     }); 
    }, 
    get: function (url, data) { 
     return $.ajax({ 
      url: url, 
      type: 'GET', 
      cache: false, 
      contentType: 'application/json; charset=utf-8', 
      data: data 
     }); 
    } 
}; 
// some awesome code later... 
serverComm.post(editGroupNameUrl, { groupId: group.id, name: newName }) 
+0

而参数是Form参数吗?有没有机会在QueryString上? – ivowiblo 2012-03-01 15:28:31

+0

QueryString为空。你是什​​么意思“是形式参数”?您可以在顶部代码示例 – soniiic 2012-03-01 15:32:07

+0

中看到我的操作,您可以发布表单代码吗? – ivowiblo 2012-03-01 15:34:14

回答

42

你的代码不工作的原因是因为你正在发送你的请求作为JSON字符串。因此,POST正文中没有请求参数,您无法在Request.Params中获取它们。

所以不是:

filterContext.HttpContext.Request.Params["groupId"] 

使用:

filterContext.Controller.ValueProvider.GetValue("groupId").AttemptedValue 

这将查询值提供商(你的情况JsonValueProvider)来获取客户端发送相应的值。

+0

它将在authorizeattribute中工作吗? – Dragon 2017-04-17 12:56:36

1

尝试没有stringify我猜MVC是除了请求参数 - >动作参数理解另一种绑定方式。它是了解json发布的。 JQuery,如果你传递数据对象(没有stringify)将发布每个字段作为请求参数(至少,我认为是这样)。这很容易尝试:)