Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
588 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - Getting the values of action parameters within an action filter

I have an action that I am POSTing to from jquery:

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

This works fine with the groupId and name. I have a few other group actions so I would like to use an authorisation attribute to make sure the person performing the change has permission to make the change.

I already have an AuthorizationAttribute that retrieves the groupId successfully on GET requests by accessing filterContext.HttpContext.Request.Params["groupId"] but when it comes to POSTs it doesn't work. The Request.Form is empty and so is Request.Params.

Here's the code I have in my authorisation attribute:

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);
}

I have looked at this answer but my Form property is empty :(

Updated to show jquery post:

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 })
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The reason your code doesn't work is because you are sending your request as a JSON string. So there are no request parameters in the POST body and you cannot fetch them in the Request.Params.

So instead of:

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

use:

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

This will query the value provider (in your case the JsonValueProvider) to obtain the corresponding value send by the client.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...