在Request.Body中绑定到JSON时,处理NancyFX中的ModelBindingException的多个绑定错误

时间:2016-09-09 18:13:21

标签: c# json model-binding nancy

我有一个帖子路由,在请求正文中接受一些JSON有效负载。

Post["/myroute/}"] = _ =>
{
    try
    {
       var model = this.Bind<MyModel>();
    }
    catch (ModelBindingException e)  
    {
       //PropertyBindException list is empty here, 
       //so only the first exception can be handled...
    }
}

如果有多个无效数据类型(即如果在MyModel中定义了几个int属性,并且用户发布了这些属性的字符串),我想传回一个很好的列表来解决这些错误,类似于如何使用ModelState一个vanilla ASP.NET MVC应用程序中的字典。

在尝试将请求正文中的JSON有效负载绑定到NancyFX中的模型时,如何完成此类异常处理?

更新

在此处查看Nancy源中的DefaultBinder: https://github.com/sloncho/Nancy/blob/master/src/Nancy/ModelBinding/DefaultBinder.cs

我看到的问题是在这个块中:

        try
        {
            var bodyDeserializedModel = this.DeserializeRequestBody(bindingContext);
            if (bodyDeserializedModel != null)
            {
                UpdateModelWithDeserializedModel(bodyDeserializedModel, bindingContext);
            }
        }
        catch (Exception exception)
        {
            if (!bindingContext.Configuration.IgnoreErrors)
            {
                throw new ModelBindingException(modelType, innerException: exception);
            }
        }

Deserialize调用似乎是&#34;全部或全部&#34;它由一个普通的异常处理,而不是一个ModelBindException,所以我在这里也看不到任何PropertyBindExceptions。

我是否需要为此实现自定义内容??

1 个答案:

答案 0 :(得分:0)

添加自己的自定义正文序列化程序,使用newtonsoft来忽略错误:

 public class CustomBodyDeserializer : IBodyDeserializer
{
    private readonly MethodInfo deserializeMethod = typeof(JavaScriptSerializer).GetMethod("Deserialize", BindingFlags.Instance | BindingFlags.Public);
    private readonly JsonConfiguration jsonConfiguration;
    private readonly GlobalizationConfiguration globalizationConfiguration;

    /// <summary>
    /// Initializes a new instance of the <see cref="JsonBodyDeserializer"/>,
    /// with the provided <paramref name="environment"/>.
    /// </summary>
    /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
    public CustomBodyDeserializer(INancyEnvironment environment)
    {
        this.jsonConfiguration = environment.GetValue<JsonConfiguration>();
        this.globalizationConfiguration = environment.GetValue<GlobalizationConfiguration>();
    }

    /// <summary>
    /// Whether the deserializer can deserialize the content type
    /// </summary>
    /// <param name="mediaRange">Content type to deserialize</param>
    /// <param name="context">Current <see cref="BindingContext"/>.</param>
    /// <returns>True if supported, false otherwise</returns>
    public bool CanDeserialize(MediaRange mediaRange, BindingContext context)
    {
        return Json.IsJsonContentType(mediaRange);
    }

    /// <summary>
    /// Deserialize the request body to a model
    /// </summary>
    /// <param name="mediaRange">Content type to deserialize</param>
    /// <param name="bodyStream">Request body stream</param>
    /// <param name="context">Current context</param>
    /// <returns>Model instance</returns>
    public object Deserialize(MediaRange mediaRange, Stream bodyStream, BindingContext context)
    {            

        //var serializer = new JavaScriptSerializer(this.jsonConfiguration, this.globalizationConfiguration);

        //serializer.RegisterConverters(this.jsonConfiguration.Converters, this.jsonConfiguration.PrimitiveConverters);

        if (bodyStream.CanSeek)
        {
            bodyStream.Position = 0;
        }

        string bodyText;
        using (var bodyReader = new StreamReader(bodyStream))
        {
            bodyText = bodyReader.ReadToEnd();
        }

       // var genericDeserializeMethod = this.deserializeMethod.MakeGenericMethod(context.DestinationType);

       // var deserializedObject = genericDeserializeMethod.Invoke(serializer, new object[] { bodyText });


        object deserializedObject = JsonConvert.DeserializeObject(bodyText, context.DestinationType, new JsonSerializerSettings
        {
            Error = HandleDeserializationError
        });

        return deserializedObject;
    }

    public void HandleDeserializationError(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs errorArgs)
    {
        string currentError = errorArgs.ErrorContext.Error.Message;
        errorArgs.ErrorContext.Handled = true;
    }
}