Getting the values of action parameters within an

2019-02-02 03:24发布

问题:

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

回答1:

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.



回答2:

Try without the stringify. I guess MVC is understanding another way of binding besides the request parameter -> action parameter. I guess it's understanding the json posted. JQuery, if you pass just the data object (without stringify) will post each field as a request parameter (at least, I think so). It's easy to try :)