Gab*_*jár 9 .net c# json http nancy
我的模块中有一条路线应该接受代表博客帖子的JSON主体.问题是请求正文不是seralized.如果我调试我在请求上看到以下值:
this.Request.Body.Length: 93
x.Keys.Count: 0
Run Code Online (Sandbox Code Playgroud)
路线
Post["/Blog"] = x =>
{
var post = this.Bind<Post>(); //Breakpoint
PostService.Save(post);
return post;
};
Run Code Online (Sandbox Code Playgroud)
HTTP请求
POST /Blog HTTP/1.1
Host: localhost:57888
Content-Type: application/json
Cache-Control: no-cache
{ "Post": { "Title":"Hello", "Content":"World", "Created":"2014-04-26" } }
Run Code Online (Sandbox Code Playgroud)
Phi*_*ill 15
您的代码没有问题,问题是您已经包装了JSON:
您的对象有一个名为的属性Post,然后它有实际的帖子.
更新你的身体看起来像:
{ "Title":"Hello", "Content":"World", "Created":"2014-04-26" }
这很可能与您Post对象上的属性匹配.
下面是对客户端的序列化,而不是问题的要求
您需要添加Accept标题.
我在这里写过关于Nancy Conneg的文章:
http://www.philliphaydon.com/2013/04/22/nancyfx-revisiting-content-negotiation-and-apis-part-1/
您的方案不起作用,因为您只是告诉服务器您的内容是什么,而不是您期望的回报.
使用Chrome插件 - 邮差,您可以测试您的方案,类似于:

通过应用Accept标头,application/json返回的内容将被序列化.
或者,您可以将.jsonURL 添加到最后以将其作为JSON返回:
http://yoursite.com/blog.json
这将迫使JSON序列化器启动.
如果您想始终返回JSON,则可以使用返回结果 .AsJson()
Post["/Blog"] = x =>
{
var post = this.Bind<Post>(); //Breakpoint
PostService.Save(post);
return Response.AsJson(post);
};
Run Code Online (Sandbox Code Playgroud)
注意,如果你要返回一个dynamic类型,那么你需要将它强制转换:return Response.AsJson((object)post);
| 归档时间: |
|
| 查看次数: |
6615 次 |
| 最近记录: |