5

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.

Béranger
  • 671
  • 8
  • 23
onlynitins
  • 75
  • 1
  • 1
  • 7

1 Answers1

8

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"
    }
]
Martin
  • 1,634
  • 1
  • 11
  • 24
  • interesting, I will give it a shot. Please let me know what will the model look like in this case. – onlynitins Jul 13 '15 at 01:58
  • It will return your .json file, so what ever is in your .json file will be returned. So that should contain valid json – Martin Jul 13 '15 at 07:39
  • `Server.MapPath` may not work for some users please see the following solution: http://stackoverflow.com/a/11105933/3997521 – petrosmm Jul 21 '16 at 00:56
  • @Martin, thanks for the answer, I am fairly new to .Net/C#, now I wanted to consume the same ApiController for load the local JSON file, how can I pass the ApiController in AJAX URL, would it be /api/JsonFileController? function loadColorPalette() { $.ajax({ url: '/api/JsonFileController', type: 'GET', dataType: "json", success: function (data) { console.log("success", data); }, error: function (err) { console.error("error", err); } }); I believe, it's not the right URL, isn't it? – Mohammad Arif Mar 11 '17 at 18:22