Reputation: 11
I am trying to build a simple API with NancyFX, hosted with ASP.NET. When http://myapp/api/get is called, it should return some JSON which is stored in a file called "data.json", which is stored on the root level along with the main module. Also, http://myapp/api/set should set the contents of the JSON file.
My initial approach was this:
Get["/api/get"] = _ =>
{
string allText = System.IO.File.ReadAllText(@"c:\data.json");
object jsonObject = JsonConvert.DeserializeObject(allText);
return jsonObject;
}
Post["/api/set"] = parameters =>
{
string json = JsonConvert.SerializeObject(parameters);
System.IO.File.WriteAllText(@"c:\data.json", json);
return HttpStatusCode.OK;
}
However, the program can't find the file in runtime. After reading some answers in here, i tried doing the following (which didn't work either):
Get["/api/get"] = _ =>
{
return new GenericFileResponse(Directory.GetCurrentDirectory() + @"\sitefiles\data.json", "application/json");
}
The answers i found were from 2011, so i suspect that's why they don't work. What is the updated way to solve this?
Upvotes: 0
Views: 342
Reputation: 11
After working a bit more, i have found a solution. You have to make a class model representing the data you are going to recieve, in this case the model is called InfoModel. Then i coded the Get and Post as such:
Get["/api/get"] = _ =>
{
DefaultRootPathProvider pathProvider = new DefaultRootPathProvider();
return new GenericFileResponse(pathProvider.GetRootPath() + "data.json", "application/json");
};
Post["/api/set"] = parameters =>
{
DefaultRootPathProvider pathProvider = new DefaultRootPathProvider();
var model = this.Bind<InfoModel>();
string json = JsonConvert.SerializeObject(model);
File.WriteAllText(pathProvider.GetRootPath() + "data.json", json);
return HttpStatusCode.OK;
};
Upvotes: 1