Nowadays JSON is more common than XML, Most of the JavaScript frameworks work well with JSON contents, AngularJS is an excellent example. Default WebAPI have IEnumerable<string> Get() and string Get(int id) methods
Take a look
Take a look
public class DefaultController : ApiController { // GET api/default2 public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/default2/5 public string Get(int id) { return "value"; } // POST api/default2 public void Post([FromBody]string value) { } // PUT api/default2/5 public void Put(int id, [FromBody]string value) { } // DELETE api/default2/5 public void Delete(int id) { } }
If you wish to return a JSON instead of string from WebAPI 2 may face some issues, So How can it resolved? You can return HttpResponseMessage instead of string or IEnumerable
[Route("api/Default/GetProductLookup/{id}")] public HttpResponseMessage GetProductLookup(string id) { string json = "Your JSON String"; var response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent(json, Encoding.UTF8, "application/json"); return response; }Here is the whole class
public class DefaultController : ApiController { // GET api/default2 public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/default2/5 public string Get(int id) { return "value"; } [Route("api/Default/GetProductLookup/{id}")] public HttpResponseMessage GetProductLookup(string id) { string json = "Your JSON String"; var response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent(json, Encoding.UTF8, "application/json"); return response; } // POST api/default2 public void Post([FromBody]string value) { } // PUT api/default2/5 public void Put(int id, [FromBody]string value) { } // DELETE api/default2/5 public void Delete(int id) { } }
No comments:
Post a Comment