Get a table data from database using WebApi & Entity Framework 6.XX

asp.net-web-api2 c# entity-framework-6 sql-server

Question

i made a Entity Data Model From Database Table Like this. enter image description here

Then add 4 line of codes in WebApiConfig.cs to get json data from response.

var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
        json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        config.Formatters.Remove(config.Formatters.XmlFormatter);

Then i created a Controller (Web API 2 controller with read/Write action) named importController.

then i added this codes to add and retrieve data from database. but not working.

    CodeXenETSEntities db = new CodeXenETSEntities();  

    [HttpPost]
    [ActionName("pushlocation")]
    // POST: api/pushlocation  
    public HttpResponseMessage pushlocation( int userid,decimal longitude, decimal latitude , TimeSpan time )
    {
        user_locations ulog = new user_locations();
        ulog.user_id = userid;
        ulog.lon = longitude;
        ulog.lat = latitude;
        ulog.time = time;
        db.user_locations.Add(ulog);
        db.SaveChanges();
        return Request.CreateResponse(HttpStatusCode.Accepted, "Successfully Created");
    }


    [HttpGet]
    [ActionName("pulllocation")]
    // GET: api/pulllocation/5  
    public HttpResponseMessage pulllocation(int userid, decimal longitude, decimal latitude, TimeSpan time)
    {

        db.user_locations.ToList();
        return Request.CreateResponse(HttpStatusCode.Accepted, "Success");
    }

this is the output : enter image description here

Database Data :

enter image description here

1
2
9/15/2016 7:58:24 PM

Accepted Answer

3 things:

1) In WebApiConfig.cs use routeTemplate: "api/{controller}/{action}/{id}"

2) In importController change public HttpResponseMessage pulllocation(int userid, decimal longitude, decimal latitude, TimeSpan time) to public HttpResponseMessage pulllocation()

3) In Browser address bar use http://localhost:57715/api/{controller name}/pulllocation. in your case http://localhost:57715/api/import/pulllocation

I hope this will solve

1
9/16/2016 1:37:57 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow