【问题标题】:Getting the values of action parameters within an action filter获取动作过滤器中动作参数的值
【发布时间】:2012-03-01 15:21:48
【问题描述】:

我有一个要从 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 })

【问题讨论】:

  • 而且参数是Form参数?有没有可能在 QueryString 上?
  • 查询字符串为空。你是什​​么意思“作为表单参数”?您可以在顶部代码示例中看到我的操作
  • 可以发一下表格代码吗?
  • 更新帖子以显示 jquery 发布数据
  • 您确定需要 JSON.stringify(data) 吗?我想你只需要把代表数据的 json 对象放上去

标签: asp.net-mvc-3


【解决方案1】:

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

所以而不是:

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

使用:

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

这将查询值提供者(在您的情况下为 JsonValueProvider)以获取客户端发送的相应值。

【讨论】:

    【解决方案2】:

    尝试不使用字符串化。我猜MVC正在理解除了请求参数->动作参数之外的另一种绑定方式。我想这是理解发布的json。 JQuery,如果您只传递数据对象(不带字符串化),则会将每个字段作为请求参数发布(至少,我认为是这样)。很容易尝试:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-21
      • 2013-04-20
      • 2017-05-06
      • 2022-05-20
      相关资源
      最近更新 更多