How do I write a post method that accepts JSON in Nancy, and how do I call it from a C# client?
Tapo
I wrote the following module in Nancy
public class CategoryModule : NancyModule
{
public CategoryModule()
{
//At this moment just Show Hello world
Get["/"] = _ => { return "Nancy says hello!"; };
//Get["/"] = parameters => "Hello World!";
GetCategories();
SetCategory();
}
void GetCategories()
{
Get["/Catergories"] = _ =>
{
var catergoryRepository = new CategoryRepository();
var categorycollection = catergoryRepository.GetCategoryInfo();
return Negotiate.WithStatusCode(HttpStatusCode.OK).WithModel(categorycollection.ToArray());
};
}
void SetCategory()
{
Post["/Catergories/{categryName:string}"] = _ =>
{
var catergoryModel = this.Bind<Category>();
catergoryModel.PK_CategoryId = Guid.NewGuid();
catergoryModel.CategoryName = _;
return HttpStatusCode.OK;
};
}
}
I am using chrome POSTMAN to test the module. If I call http://192.168.1.4:8888/Categories in POSTMAN, I can get breakpoints in "GetCategories()" . But if I call http://192.168.1.4:8888/Catergories/categryName=test, I ca n't get the breakpoint in SetCategory() . I'm new to Nancy and not sure if my method of posting is correct.
anyone can provide
- Example of Post method accepting Jason as parameter
- Example of calling it from client
I couldn't find the simple example above in their documentation.
Notice
I'm hosting Nancy's self-hosted environment with the following code
var server = new Nancy.Hosting.Self.NancyHost(new Uri("http://192.168.1.4:8888"));
Below is the category model
public class Category
{
public Guid PK_CategoryId { get; set; }
public string CategoryName { get; set; }
}
Roman Dubicin
If you want to use POSTMAN to post JSON, you should add the JSON-Content-Type header as described in the documentation (third paragraph). Set up POSTMAN:
- Set the host to,
http://192.168.1.4:8888/Categories
then selectPOST
. - Add headers with
Content-Type
andapplication/json
as header and value respectively. - Set
raw
and setJSON
to type. - Put it in
{ "CategoryName": "something" }
the text field below. - Click "Send".