Created
November 17, 2011 21:04
-
-
Save andlju/1374519 to your computer and use it in GitHub Desktop.
Sample that shows how to bind by type in Nancy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
POST http://localhost:2835/BindByType/FirstType | |
Content-Type: application/json | |
Content-Length: 49 | |
{ | |
"Prop1":"Testing", | |
"Prop2":"Second Test" | |
} | |
----- | |
HTTP/1.1 200 OK | |
Nancy-Version: 0.9.0.0 | |
Content-Type: text/html | |
Content-Length: 18 | |
Works brilliantly! |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace NancyTest | |
{ | |
public class FirstType | |
{ | |
public string Prop1 { get; set; } | |
public string Prop2 { get; set; } | |
} | |
public class SecondType | |
{ | |
public string Test { get; set; } | |
} | |
public class TestModule : NancyModule | |
{ | |
public TestModule() | |
{ | |
Post["/BindByType/{typeName}"] = _ => | |
{ | |
// Get the type | |
var typeName = Context.Parameters["typeName"]; | |
var myType = Type.GetType("NancyTest." + typeName + ", NancyTest"); | |
// Find a binder for this type | |
var binder = ModelBinderLocator.GetBinderForType(myType); | |
// Use the binder to get a bound instance of the type | |
object boundObj = binder.Bind(Context, myType); | |
// Make sure it works | |
if (boundObj.GetType().Name == typeName) | |
return "Works brilliantly!"; | |
return "Won't happen"; | |
}; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment