Following is my code snippet which works fine, my query follows the code:
Model:
namespace CVHub.Models
{
[DataContract]
public class Context
{
[DataMember]
public int sessionID { get; set; }
[DataMember]
public string Name { get; set; }
public static List <Context> Contexts= new List<Context>
{
new Context{sessionID=1,Name="Name1"},
new Context {sessionID=2,Name="Name2"},
new Context {sessionID=3,Name="Name3"}
};
}
}
Controller:
namespace CVHub.Controllers
{
public class ContextController : ApiController
{
List<Context> items;
// GET api/values
public IEnumerable<Context> Get()
{
//return Context.Contexts;
return items;
}
}
}
Question: I want to use an external json file (residing in app_data folder) to serve same data instead of doing new Context{sessionID=1,Name="Name1"},
how to use a data I read from json file? I am very new to MVC and webApi, so it will be of great help if the experts can post the entire working code or as much details as possible please.
The JSON data source parses the input JSON expression by using JSONPath and populates the specified properties with the parsed values. In this topic, we focus on how to configure the JSON data source. We assume you are already familiar with data-driven testing and how to configure a data-driven loop.
You can return a HttpResponseMessage
with your JSON file loaded into StringContent
.
public class JsonFileController : ApiController
{
public HttpResponseMessage Get()
{
var json = File.ReadAllText(Server.MapPath(@"~/App_Data/contexts.json");
return new HttpResponseMessage()
{
Content = new StringContent(json, Encoding.UTF8, "application/json"),
StatusCode = HttpStatusCode.OK
};
}
}
App_Data/contexts.json
[
{
"sessionId": 1,
"name": "name1"
},
{
"sessionId": 2,
"name": "name2"
},
{
"sessionId": 3,
"name": "name3"
}
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With