加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-3 – 在动作过滤器中获取动作参数的值

发布时间:2020-12-15 18:43:09 所属栏目:asp.Net 来源:网络整理
导读:我有一个我从jquery发布的动作: [HttpPost]public void UpdateGroupName(int groupId,string name){ authorisationRepository.UpdateGroupName(groupId,name);} 这对groupId和名称很好。我还有一些其他的群组操作,所以我想使用授权属性来确保执行更改的人
我有一个我从jquery发布的动作:
[HttpPost]
public void UpdateGroupName(int groupId,string name)
{
    authorisationRepository.UpdateGroupName(groupId,name);
}

这对groupId和名称很好。我还有一些其他的群组操作,所以我想使用授权属性来确保执行更改的人有权进行更改。

我已经有一个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,type: 'GET',cache: false,data: data
        });
    }
};
// some awesome code later...
serverComm.post(editGroupNameUrl,{ groupId: group.id,name: newName })

解决方法

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

所以,而不是:

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

使用:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读