问题
This really seems like a framework bug. The parameter is in the request's params with correct name but it doesnt always bind to the action parameter. It worked for 6 months, but now this is happening in several action methods across the application.
I was able to either close VS or restart computer and that would usually fix it. Lately when i've run into this i couldnt get by it without turning the paramter into a string and then converting to a GUID.
Any advice on what to do with this since we have many action methods accepting nullable Guids and its a pain to have to manually convert the parameter.
I dont want a workaround for this, i want to know if anyone knows how i could debug this or what they think might be going on. It is random and inconsistent.
thanks!
回答1:
Without actually having had this problem myself my initial thoughts would be that this is a problem with the actual values being passed in from the browser.
I've debugged a similar issue like this with nullable DateTimes and was able to get around it by writing a custom model binder and setting it up to only bind DateTime? types.
By doing this, you can inspect the values getting passed in and check them for any anomalies.
It's pretty straight forward to do. In you global.asax:
ModelBinders.Binders.Add(typeof(guid?), new GuidModelBinder());
And then create a class
public class GuidModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
var modelState = new ModelState { Value = valueResult };
}
//Do whatever you need to inspect the valueResult in here
}
回答2:
That is, indeed, very strange behavior. To debug it, you may want to check out ASP.NET MVC's source code. You could then "step into" the ModelBinder's methods.
You may also want to try creating a custom model binder. First of all, this would give you an easier place to put a break point if you want to step into MVC's built-in methods. But it would also give you a chance to log what's happening (to identify the cases where the binding fails, e.g.), as well as potentially using your own code to ensure the model binds correctly once you identify the root of the problem.
Before you go too far, you should probably check whether you're already using a custom model binder, and if you are, check it for potential bugs. You should also ensure that your model class is as simple as it can possibly be, and not subject to possible race conditions or other weirdness.
来源:https://stackoverflow.com/questions/8086849/mvc-action-parameter-inconsistently-binds-to-nullable-guid