ASP .NET MVC 3 based Facebook app: parse query str

2019-04-13 04:39发布

问题:

In a nutshell: Facebook passes my MVC 3 application the following query string after a user selects friends with the fb:request-form control:

http://apps.facebook.com/my_app/?...&ids[]=100001694177427&ids[]=100001178061757

I assumed the default model binder would parse the ids[] array in the query string and bind it to my ids parameter in the action below:

public ActionResult Index(long[] ids)
{
   //...
   return View();
}

This previous question appeared to backup my thinking: In ASP.NET MVC 2, can I deserialize a querystring into an array using the default ModelBinder?

However, I still receive a null value. I've tried every parameter type I can think of, but to no avail. I can see from my controller's ValueProvider that it's definitely coming through (and being parsed as an array), so thought I would post here for ideas before working through the ModelBinder source!

Thanks in advance for any help.

回答1:

Looking at the source it appears to be looking for indexes that contain [0], [1], [2]... rather than allowing for []. Seems an interesting oversight.

However, you can create a custom modelbinder by doing the following:

public class IdList : List<long> { }

This is a class to hold our ids

public class IdListModelBinder : IModelBinder {
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
        var x = bindingContext.ValueProvider.GetValue("ids[]");

        IdList list = new IdList();
        foreach (var value in (string[])x.RawValue) {
            //replace this with proper validation of values
            list.Add(long.Parse(value));
        }

        return list;
    }
}

Then in the controller you would do something like:

public ActionResult Index(IdList ids) {
    return View();
}

In your global.asax you would add the following line to your Application_Start method

ModelBinders.Binders.Add(typeof(IdList), new IdListModelBinder());