问题
I'm just starting to play with NancyFx to compare it with the .net MVC WebAPI stuff and I've hit an issue straight away. As I understand it Nancy should handle serialization straight out of the box. But I can't seem to get it working.
I have a Nancy Module that looks like this:
public class HelloWorld : NancyModule
{
public HelloWorld()
{
Post["/"] = parameters =>
{
var myFieldValue = parameters.myField;
return HttpStatusCode.OK;
};
}
}
And I post to it using Fiddler like this:
Headers:
User-Agent: Fiddler
Content-Type: application/json
Host: localhost:3141
Content-Length: 24
Request-Body:
{"myField" : "profit"}
However when the parameters object is empty (and so, therefore is the myFieldValue object). I'm sure I've missed something really obvious, but I don't know what!
回答1:
Parameters are for captures in the url (e.g. /foo/{bar} would capture a bar variable in parameters. If you are posting JSON you should use the model binder (var foo =this.Bind();
I would recommend taking a look at the docs too.. All of this is covered there :-)
回答2:
For posting data you have to use model binding. Unfortunately, model binding to dynamic is not supported and you have to create request classes. There is a proposed workaround , but I didn't use it myself.
If you don't want to define class for particular request and use model binding, then you can use power of dynamic
with json.net.
Example:
public AuthTokenModule (IAuthService authService, UserMapper mapper) : base ("api/v1/authToken")
{
Post ["/login"] = x => {
dynamic request = JsonConvert.DeserializeObject (Request.Body.AsString ());
var user = mapper.ValidateUser ((string)request.email, (string)request.password);
来源:https://stackoverflow.com/questions/18418124/nancyfx-posting-json-nancy-dynamicdictionary-is-empty