user326502 user326502 - 2 months ago 25
C# Question

NancyFx binding a model to a dynamic type?

In Nancy, is there a way to bind the content of a POST request to a dynamic type?

For example:.

// sample POST data: { "Name": "TestName", "Value": "TestValue" }

// model class
public class MyClass {
public string Name { get; set; }
public string Value { get; set; }
}

// NancyFx POST url
Post["/apiurl"] = p => {

// this binding works just fine
var stronglyTypedModel = this.Bind<MyClass>();

// the following bindings do not work
// there are no 'Name' or 'Value' properties on the resulting object
dynamic dynamicModel1 = this.Bind();
var dynamicModel2 = this.Bind<dynamic>();
ExpandoObject dynamicModel3 = this.Bind();
var dynamicModel4 = this.Bind<ExpandoObject>();

}

Answer

Out of the box Nancy does not support dynamic model binding. TheCodeJunkie has written a quick ModelBinder to achieve that tho.

https://gist.github.com/thecodejunkie/5521941

Then you can use it like so

dynamic model = this.Bind<DynamicDictionary>();