.Net Rest Api Example - Asp.net

How to use rest api in .net?

Snippet Code


  
Rate this page :
  [ 0 votes]

The name .net rest api which refers that the api will run in server side like json object. Normally the names of properties are converted into camel case in json while serializing. Run the code in browser like
localhost:2464/api/ptemployees/1000.
Then the json details of 1000 employees id are fetched through this code.

[EnableCors(origins: "http://localhost:55058", headers: "*", methods: "*")] public class PTEmployeesController : ApiController { // GET api/ptemployees [Route("api/ptemployees")] public HttpResponseMessage Get() { var employees= EmployeesRepository.GetAllEmployees(); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, employees); return response; } // GET api/ptemployees/5 [Route("api/ptemployees/{id?}")] public HttpResponseMessage Get(int id) { var employees = EmployeesRepository.GetEmployee(id); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, employees); return response; } [Route("api/ptemployees/{name:alpha}")] public HttpResponseMessage Get(string name) { var employees = EmployeesRepository.SearchEmployeesByName(name); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, employees); return response; } [Route("api/ptemployees")] public HttpResponseMessage Post(Employee e) { var employees = EmployeesRepository.InsertEmployee(e); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, employees); return response; } [Route("api/ptemployees")] public HttpResponseMessage Put(Employee e) { var employees = EmployeesRepository.UpdateEmployee(e); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, employees); return response; } [Route("api/ptemployees")] public HttpResponseMessage Delete(Employee e) { var employees = EmployeesRepository.DeleteEmployee(e); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, employees); return response; } }

Tags


Ask Questions

Ask Question