Nancy Model绑定到子类。自动检测?

时间:2018-09-16 18:05:52

标签: c# .net nancy

我想知道是否可以让Nancy自动将请求绑定到我在类型参数中指定的类型的子类。这是我要实现的目标的一个示例:

给出以下类别:

public class Shape
{
    public int Height { get; set; }
    public int Width { get; set; }
}

public class Triangle : Shape
{
    public string SomeTriangleOnlyProp { get; set; }
}

public class Square : Shape
{
    public string SomeSquareOnlyProp { get; set; }
}

然后给这个杰森:

{
    "Height" : 10,
    "Width" : 20
}

然后这是我想要的结果:

var shape = this.Bind<Shape>(); //Returns a Shape object

给出这个Json:

{
    "Height" : 10,
    "Width" : 20,
    "SomeTriangleOnlyProp" : "Triangle"
}

然后这是我想要的结果:

var shape = this.Bind<Shape>(); //Returns a Triangle object

给出这个Json:

{
    "Height" : 10,
    "Width" : 20,
    "SomeSquareOnlyProp" : "Square"
}

然后这是我想要的结果:

var shape = this.Bind<Shape>(); //Returns a Square object

我只能使用自定义绑定类来实现吗?我可以尝试分别绑定到每种类型并处理任何错误,但这似乎并不是最佳选择。

1 个答案:

答案 0 :(得分:0)

我已经找到了一种解决方案,我不确定这是否是最好的解决方案,但是它可以满足我的需求,因此这就是我现在要使用的解决方案。我已经编写了一个自定义模型活页夹,该活页夹将查看json并尝试确定应序列化到的对象:

public class ShapeBinder : IModelBinder
{
    public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList)
    {
        using (var sr = new StreamReader(context.Request.Body))
        {
            var json = sr.ReadToEnd();
            if (json.Contains("SomeTriangleOnlyProp"))
            {
                var triangle = new Nancy.Json.JavaScriptSerializer().Deserialize<Triangle>(json);
                return triangle;
            }
            else if (json.Contains("SomeSquareOnlyProp"))
            {
                var square = new Nancy.Json.JavaScriptSerializer().Deserialize<Square>(json);
                return square;
            }
            else
            {
                var shape = new Nancy.Json.JavaScriptSerializer().Deserialize<Shape>(json);
                return shape;
            }
        }
    }

    public bool CanBind(Type modelType)
    {
        return modelType == typeof(Shape);
    }
}

如果NancyModulevar shape = this.Bind<Shape>();调用,则返回JSON的三角形Triangle,如果Square包含正方形的prop,则返回Shape。常规基//On key up enter or pressing enter function checkForEnter() { var input = document.getElementById("userinches"); input.addEventListener("keyup", function(event) { event.preventDefault(); //check if input has a greater than zero if (input.value.length > 0 && event.keyCode === 13) { document.getElementById("buttonft").click(); } }); } checkForEnter(); // converting the value to feet in 2 fixed decimal function feet() { var userinches = document.getElementById('userinches').value; doOuput('The answer is ', userinches * 0.0833).toFixed(2); //doOuput('The answer is ', userinches * 0.0833); } function doOuput(val, unit) { document.getElementById('results').innerHTML = val + unit; //document.getElementById('results').innerHTML = val + unit.toFixed(2); }类(如果JSON都没有)。