微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我有一个我从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)以获取客户端发送的相应值。

原文地址:https://www.jb51.cc/aspnet/253716.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐