MVC操作参数不一致地绑定到可为空的Guid [英] MVC action parameter inconsistently binds to nullable Guid

查看:81
本文介绍了MVC操作参数不一致地绑定到可为空的Guid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎确实是一个框架错误.该参数在请求的参数中具有正确的名称,但它并不总是绑定到action参数.它已经工作了6个月,但是现在在整个应用程序中的几种操作方法中都发生了这种情况.

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.

我能够关闭VS或重新启动计算机,通常可以解决该问题.最近,当我遇到这个问题时,我无法通过它而没有将参数转换为字符串,然后转换为GUID.

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.

关于此操作的任何建议,因为我们有许多操作方法接受可为空的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.

谢谢!

推荐答案

我自己实际上没有遇到这个问题,我最初的想法是这是从浏览器传递实际值的问题.

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.

我用可为空的DateTimes调试了类似的问题,并且能够通过编写自定义模型绑定程序并将其设置为仅绑定DateTime来解决此问题?类型.

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.

这很简单.在您的global.asax中:

It's pretty straight forward to do. In you global.asax:

ModelBinders.Binders.Add(typeof(guid?), new GuidModelBinder());

然后创建一个类

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
    }

这篇关于MVC操作参数不一致地绑定到可为空的Guid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆