nancyfx posting json - Nancy.DynamicDictionary is empty

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-03 18:19:23

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!