使用asp.net 开发webapi 中的put功能

标签: put

功能:更新指定id的记录。

1、代码。

   public  HttpResponseMessage Put(int id, [FromBody] Employee employee)
        {
            try
            {
                using (EmployeeDBEntities entities = new EmployeeDBEntities())
                {
                    var entity = entities.Employees.FirstOrDefault(e => e.Id == id);
                    if (entity == null)
                    {
                        var message = String.Format("employee with id: {0} was not found", id);
                        var errorResponse = Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
                        throw new HttpResponseException(errorResponse);
                    }
                    else
                    {
                        entity.FirstName = employee.FirstName;
                        entity.LastName = employee.LastName;
                        entity.Gender = employee.Gender;
                        entity.Salary = employee.Salary;

                        entities.SaveChanges();

                        var response = Request.CreateResponse(HttpStatusCode.OK, entity);
                        response.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddSeconds(300));
                        return response;
                    }
                }
            }
            catch(Exception ex)
            {
             var errorResponse = Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
                throw new HttpResponseException(errorResponse);
                
            }
        }

2、测试。(通过postman)

3、结果。

版权声明:本文为winniezhang原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/winniezhang/article/details/103445312