c# - Nancy decimal 属性绑定(bind)不起作用

标签 c# nancy

我在绑定(bind)小数属性时遇到问题:

Oh noes! ---> Nancy.ModelBinding.ModelBindingException: Unable to bind to type: Nancy.Models.SomeModel
at Nancy.ModelBinding.DefaultBinder.Bind(NancyContext context, Type modelType, Object instance, BindingConfig configuration, String[] blackList)
at Nancy.ModelBinding.DynamicModelBinderAdapter.TryConvert(ConvertBinder binder, Object& result)
at CallSite.Target(Closure , CallSite , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
at Nancy.ModelBinding.ModuleExtensions.Bind[TModel](INancyModule module)
at KBZServisNancy.Modules.SomeModule.<.ctor>b__2(Object x) in d:\Nancy\Modules\SomeDecimalModule.cs:line 38
at CallSite.Target(Closure , CallSite , Func`2 , Object )
at Nancy.Routing.Route.<>c__DisplayClass4.b__3(Object parameters, CancellationToken context)
--- End of inner exception stack trace ---
at Nancy.NancyEngine.InvokeOnErrorHook(NancyContext context, ErrorPipeline pipeline, Exception ex)
at Nancy.NancyEngine.InvokeOnErrorHook(NancyContext context, ErrorPipeline pipeline, Exception ex)

如果 decimal 属性的值是例如 20,50,则绑定(bind)工作正常,但如果值为 20.50,我会收到上层错误消息。据此,文化敏感可能存在问题,但上下文文化是{en-US}。已经有一些此类问题Culture model binding他们已经解决了,所以我不知道问题出在哪里。我在控制台应用程序中使用自托管的 Nancy v0.23。提前感谢您的帮助。

最佳答案

在当前的 Nancy 版本中,只需编写自己的 ITypeConverter

/// <summary>
/// Nancy converter to convert numeric types with InvariantCulture.
/// </summary>
public class NancyNumericConverter : ITypeConverter
{
    public bool CanConvertTo(Type destinationType, BindingContext context)
    {
        return destinationType.IsNumeric();
    }

    public object Convert(string input, Type destinationType, BindingContext context)
    {
        if (string.IsNullOrEmpty(input))
        {
            return null;
        }

        return System.Convert.ChangeType(input, destinationType, CultureInfo.InvariantCulture);
    }
}

(我也更新了 issue https://github.com/NancyFx/Nancy/issues/1587。)

关于c# - Nancy decimal 属性绑定(bind)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24439997/

相关文章:

c# - 通过单个套接字多次发送数据

C# 如果只初始化一些条目,数组会使用多少内存?

c# - 部署的应用程序功能有空的 host.json 并且没有主机 key

c# - 模型绑定(bind)到 Nancy 中的 Dictionary<string,string>

c# - 编译器不会让我使用三元运算符返回对象

json.net - 通过协商更改 NancyModule 中的 json.net 配置

.net - 南希 : use array of data from POST request

c# - 过滤 json 字符串中的无效值

c# - 在测试使用 JWT Bearer Authentication 的 NancyFX 网站时,我应该模拟 CurrentUser 还是添加授权 header ?

c# - 将键值对反序列化到列表中