locked
Api problem RRS feed

  • Question

  • User1979860870 posted

    Hi

    In Postman this statement is written - http://localhost:40991/api/Employees?id=1

     IN below code but Get Api are working but Delete Api not working . It is showing Status 404 not found

        public class EmployeesController : ApiController
        {
            private PMDbEntities db = new PMDbEntities();
    
            // GET: api/Employees
            public IHttpActionResult GetEmployees()
            {
                try
                {
                    var results = (from d in db.Employees
                                   join f in db.Departments
                                   on d.DepartmentId equals f.ID
                                   select new
                                   {
                                       Id = d.ID,
                                       Name = d.Name,
                                       Department = f.Description
                                   }).ToList();
                    if (results == null)
                    {
                        return NotFound();
                    }
                    return Ok(results);
                }
                catch (Exception)
                {
                    return BadRequest();
                }
            }
    
            [HttpGet]
            [ResponseType(typeof(Employee))]
            public HttpResponseMessage GetEmployee(int id)
            {
                Employee employee = db.Employees.Find(id);
                if (employee == null)
                {
                    return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Employee Code : " + id + "not found");
                }
                else
                {
                    var results = (from d in db.Employees
                                   join f in db.Departments
                                   on d.DepartmentId equals f.ID
                                   select new
                                   {
                                       Id = d.ID,
                                       Name = d.Name,
                                       Department = f.Description
                                   }).ToList();
                    return Request.CreateResponse(HttpStatusCode.OK, results);
                }
            }
            // DELETE: api/Employees/5
            [HttpDelete]
            [ResponseType(typeof(Employee))]
            public IHttpActionResult DeleteEmployee(int id)
            {
                try
                {
                    Employee employee = db.Employees.Find(id);
                    if (employee == null)
                    {
                        return BadRequest("Error Encountered : ");
                        //return Content(HttpStatusCode.NotFound, "Employee not found");
                    }
                    else
                    {
                        db.Employees.Remove(employee);
                        db.SaveChanges();
                        return Ok();
                        //(employee);
                    }
                }
                catch (Exception ex)
                {
                    return BadRequest("Error Encountered : " + ex);
                }
            }

    Thanks

    Thursday, February 25, 2021 4:18 PM

All replies

  • User1686398519 posted

    Hi jagjit saini, 

    1. It is showing Status 404 not found
      1. Generally speaking, 404 errors are caused by incorrect URLs. If you can, you can tell me how you request the DeleteEmployee method.
      2. I used the code you provided for test, as long as the URL is correct, it can be requested.
        1. The api route is the default route configuration, I have not modified it.
          •         public static void Register(HttpConfiguration config)
                    {
                        config.MapHttpAttributeRoutes();
                        config.Routes.MapHttpRoute(
                            name: "DefaultApi",
                            routeTemplate: "api/{controller}/{id}",
                            defaults: new { id = RouteParameter.Optional }
                        );
                    }
        2. Request Url: https://localhost:44365/api/employees/1   Or  https://localhost:44365/api/employees?id=1

    Best Regards,

    YihuiSun

    Friday, February 26, 2021 6:19 AM
  • User1979860870 posted

    Hi YihuiSun

       This code works for GET - http://localhost:40991/api/Employees/1

    When selected DELETE it does not works

    WebApi Config
    
    config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
                config.EnableCors(new EnableCorsAttribute("*", "*", "GET,PUT,POST,DELETE"));
    
    [HttpGet]
            [ResponseType(typeof(Employee))]
            public HttpResponseMessage GetEmployee(int id)
            {
                Employee employee = db.Employees.Find(id);
                if (employee == null)
                {
                    return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Employee Code : " + id + "not found");
                }
                else
                {
                    var results = (from d in db.Employees
                                   join f in db.Departments
                                   on d.DepartmentId equals f.ID
                                   where d.ID == id
                                   select new
                                   {
                                       Id = d.ID,
                                       Name = d.Name,
                                       Department = f.Description
                                   }).ToList();
                    return Request.CreateResponse(HttpStatusCode.OK, results);
                }
            }
    
    [HttpDelete]
            [ResponseType(typeof(Employee))]
            public IHttpActionResult DeleteEmployee(int id)
            {
                try
                {
                    Employee employee = db.Employees.Find(id);
                    if (employee == null)
                    {
                        //return BadRequest("Error Encountered : ");
                        return Content(HttpStatusCode.NotFound, "Employee not found");
                    }
                    else
                    {
                        db.Employees.Remove(employee);
                        db.SaveChanges();
                        return Ok();
                        //(employee);
                    }
                }
                catch (Exception ex)
                {
                    return BadRequest("Error Encountered : " + ex);
                }
            }

    Thanks

    Friday, February 26, 2021 6:52 AM
  • User1686398519 posted

    Hi jagjit saini, 

    When selected DELETE it does not works

    What does "not works" mean? According to what you said before, if it is a 404 error, you need to check whether the URL you requested is correct.

    In addition, I don't know what method you used to request your api method.

    1. You can see my previous answer. I tested it in Postman, and the delete method can be requested.
    2. I also use HttpClient to request the api, and I can also request the corresponding method.
      • var client = new HttpClient();
        var result = await client.DeleteAsync("https://localhost:44365/api/Employees/1");
    3. If there is no delete method in the accepted methods, an error will occur when using ajax to send the delete request on the view. However, in this case, the error that appears is 405.

    Best Regards,

    YihuiSun

    Wednesday, March 3, 2021 2:06 AM
  • User303363814 posted

    You show us something that works and then ask why something else doesn't work.

    Your first code sample is different from the second code sample.

    Your first error was 404, the second is 'does not work'

    Your second code returns 404 if the Employee is not found which makes sense.

    It is very unclear if you have a problem at all because you don't give us the information needed (like showing us the failing request and the entities in the database) and the information that you do give keeps changing.

    What, if any, basic debugging have you done?  Breakpoints?

    Wednesday, March 3, 2021 10:46 PM