Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...