Created
March 16, 2016 07:32
-
-
Save blacktambourine/4ce25c0a565b0bc9a38d to your computer and use it in GitHub Desktop.
Demo Web API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| using System.Web.Http; | |
| using System.Web.Http.Description; | |
| using MyProject.Web.Models.Common; | |
| using NLog; | |
| namespace MyProject.Web.WebApi | |
| { | |
| public class DemoController : ApiController | |
| { | |
| private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); | |
| // GET api/<controller> | |
| [HttpGet] | |
| public IEnumerable<string> GetItems() | |
| { | |
| return new [] { "value1", "value2" }; | |
| } | |
| // GET api/<controller>/5 | |
| [ResponseType(typeof(DemoModel))] | |
| [HttpGet] | |
| public IHttpActionResult GetItem(int id) | |
| { | |
| try | |
| { | |
| Logger.Info("Getting item from service"); | |
| System.Threading.Thread.Sleep(3000); //simulate wait time | |
| var result = new DemoModel { ServiceResult = "Web API Service is online", HasResponseErrors = false }; | |
| return Ok(result); | |
| } | |
| catch (Exception ex) | |
| { | |
| Logger.Error("An error occurred in the Web Api layer.", ex); | |
| return Ok(new DemoModel { HasResponseErrors = true }); | |
| } | |
| } | |
| // POST api/<controller> | |
| [ResponseType(typeof(ResponseModel))] | |
| [HttpPost] | |
| public IHttpActionResult PostItem([FromBody]string value) | |
| { | |
| if (!ModelState.IsValid) | |
| { | |
| return BadRequest(ModelState); | |
| } | |
| return Ok(new ResponseModel{ HasResponseErrors = false }); | |
| } | |
| // PUT api/<controller>/5 | |
| [ResponseType(typeof(ResponseModel))] | |
| [HttpPut] | |
| public IHttpActionResult PutItem(int id, [FromBody]string value) | |
| { | |
| if (!ModelState.IsValid) | |
| { | |
| return BadRequest(ModelState); | |
| } | |
| return Ok(new ResponseModel { HasResponseErrors = false }); | |
| } | |
| // DELETE api/<controller>/5 | |
| [ResponseType(typeof(ResponseModel))] | |
| [HttpDelete] | |
| public IHttpActionResult DeleteItem(int id) | |
| { | |
| return Ok(new ResponseModel { HasResponseErrors = false }); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment