none
Unable to test the post, put and delete method via postman. "get method via id and all employees is working" RRS feed

  • Question

  • Unable to test the post, put and delete method via postman. "get method via id and all employees is working"

    I am trying to create a test api call. I have creates a mvc form and api page for the processes like get, put post and delete.
    I am facing error when trying to test the same from postman application.

    {   "message": "The requested resource does not support http method 'POST'." }

    Sharing the code for home controller and employee controller.

    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Net;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Web.Mvc;
    using WebApplication2Test.Database;
    using WebApplication2Test.Models;

    namespace WebApplication2Test.Controllers
    {
        public class HomeController : Controller
        {

            private EmployeeDbEntities db = new EmployeeDbEntities();
            // GET: Employee

            public ActionResult Index()
            {
                IEnumerable<EmployeeViewModel> employees = null;

                using (var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }))
                {
                    string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/";
                    client.BaseAddress = new Uri(baseUrl);

                    var apiMethod = $"api/employees";

                    var response = client.GetAsync(apiMethod);

                    var result = response.Result;

                    if (result.IsSuccessStatusCode)
                    {

                        var test = result.Content.ReadAsStringAsync();
                        test.Wait();

                        var apiResponseData = test.Result;

                        employees = JsonConvert.DeserializeObject<IEnumerable<EmployeeViewModel>>(apiResponseData);


                    }

                    return View(employees);
                }
            }


            ////GET: Employee/Details/5
            //public ActionResult Details(int id)
            //{
            //    var employee = db.Employees.SingleOrDefault(e => e.ID == id);
            //    return View(employee);
            //}

            // GET: Employee/details/5
            public ActionResult Details(int id)
            {
                EmployeeViewModel employee = CallApiGetEmployeeMethod(id);

                return View(employee);

            }

            private EmployeeViewModel CallApiGetEmployeeMethod(int id)
            {

                EmployeeViewModel employee = null;

                using (var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }))
                {
                    string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/";
                    client.BaseAddress = new Uri(baseUrl);

                    var apiMethod = $"api/employees/" + id;

                    var response = client.GetAsync(apiMethod);

                    var result = response.Result;

                    if (result.IsSuccessStatusCode)
                    {

                        var test = result.Content.ReadAsStringAsync();
                        test.Wait();

                        var apiResponseData = test.Result;

                        employee = JsonConvert.DeserializeObject<EmployeeViewModel>(apiResponseData);


                    }

                    return employee;
                }

            }

            //GET: Employee/Create
            public ActionResult Create()
            {
                return View();
            }

            //POST: Employee/Create
            [HttpPost]
            public ActionResult post(EmployeeViewModel employee)
            {
                try
                {
                    using (var client = new HttpClient())
                    {

                        string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/";
                        client.BaseAddress = new Uri(baseUrl);

                        var apiMethod = $"api/employees/createemployee";

                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        var postTask = client.PostAsJsonAsync<EmployeeViewModel>(apiMethod, employee);
                        
                        postTask.Wait();

                        var result = postTask.Result;

                        if(result.IsSuccessStatusCode)
                        {
                            return RedirectToAction("Index");
                        }
                        return View();
                    }
                    
                }
                catch (Exception)
                {
                    return View();
                }
            }

            // GET: Employee/Edit/5
            public ActionResult Edit(int id)
            {
                EmployeeViewModel employee = CallApiGetEmployeeMethod(id);
                return View(employee);
            }

            //    public ActionResult Put(int id)
            //    {
            //        EmployeeViewModel employee = null;

            //        using (var client = new HttpClient())
            //        {
            //            client.BaseAddress = new Uri("https://localhost:44316//api/");
            //            //HTTP GET
            //            var responseTask = client.GetAsync("Employee?id=" + id.ToString());
            //            responseTask.Wait();

            //            var result = responseTask.Result;
            //            if (result.IsSuccessStatusCode)
            //            {
            //                var readTask = result.Content.ReadAsAsync<EmployeeViewModel>();
            //                readTask.Wait();

            //                Employee = readTask.Result;
            //            }
            //        }

            //        return View(employee);
            //    }
            //}


            // POST: Employee/Edit/5
            [HttpPost]
            public ActionResult Edit(int id, EmployeeViewModel employee)
            {
                try
                {

                    if (TryUpdateModel(employee))
                    {

                        using (var client = new HttpClient())
                        {

                            string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/";
                            client.BaseAddress = new Uri(baseUrl);

                            var apiMethod = $"api/employees/updateemployee";

                            client.DefaultRequestHeaders.Accept.Add(
                                new MediaTypeWithQualityHeaderValue("application/json"));

                            //HTTP Put
                           var putTask = client.PutAsJsonAsync<EmployeeViewModel>(apiMethod, employee);
                            //var putTask = client.PutAsync(apiMethod);

                            putTask.Wait();

                            var result = putTask.Result;
                            if (result.IsSuccessStatusCode)
                            {

                                return RedirectToAction("Index");
                            }
                        }
                    }

                    return View(employee);
                }
                catch
                {
                    return View();
                }
            }


            // GET: Employees/Delete/5
            public ActionResult Delete(int? id)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }


                using (var client = new HttpClient())
                {

                    string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/";
                    client.BaseAddress = new Uri(baseUrl);

                    var apiMethod = $"api/employees/" + id.ToString();

                    //HTTP DELETE
                    var deleteTask = client.DeleteAsync(apiMethod);

                    deleteTask.Wait();

                    var result = deleteTask.Result;
                    if (result.IsSuccessStatusCode)
                    {

                        return RedirectToAction("Index");
                    }
                }

                return RedirectToAction("Index");

            }

            // POST: Employee/Delete/5
            [HttpDelete]
            public ActionResult Delete(int id)
            {
                Employee employee = db.Employees.Find(id);
                db.Employees.Remove(employee);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            // catch
            //{
            //  return View();
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    db.Dispose();
                }

                base.Dispose(disposing);
            }
        }
    }



    • Edited by _RJ_ Saturday, November 30, 2019 10:07 AM
    • Moved by CoolDadTx Monday, December 2, 2019 3:09 PM ASP.NET related
    Saturday, November 30, 2019 9:52 AM

Answers

  • Ah, no. Given this class, your JSON is not correct.

    Your JSON starts with [ and ends with ]. This means that you are sending an array. But the EmployeeViewModel class does not inherit from List<> or otherwise represent an array.

    To send a single employee, the JSON would look like this:

        {
            "ID": 12345,
            "Name": "Test6"
        }

    The opening and closing {} mean that you are sending an object. Then you get an entry for each property of the object, which for the class EmployeeViewModel happen to be ID and Name (case sensitive!), not name and IsComplete as you had specified. Finally, note how the value for Name is enclosed in quotes because it is a string, but ID does not have quotes because it is an int.

    • Marked as answer by _RJ_ Friday, December 6, 2019 5:07 PM
    Thursday, December 5, 2019 9:23 PM

All replies

  • From your class declaration, you are creating a Controller and not an ApiController. Unless you have modified the default route map, this means that to call your post or delete actions it is not enough to specify the http method in postman. You also have to modify the Url so that it contains the Controller and the method name (which you would not need if you were using an ApiController with the default route instead of a Controller). Maybe there is your mistake. Have you verified that when testing from Postman you included the action method in the Url? If you are following a tutorial that was based on an ApiController then the examples would not have the action in the Url, but you need it for your Controller.
    Saturday, November 30, 2019 7:44 PM
  • An ASP.NET MVC WebAPI is what you should be using.

    https://www.tutorialspoint.com/asp.net_mvc/asp.net_mvc_web_api.htm

    ASP.NET solutions can be discussed at the ASP.NET forums.

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/data/using-web-api-with-entity-framework/part-1

    http://forums.asp.net/

    Saturday, November 30, 2019 9:52 PM
  • Hi

    In reference to the ask mentioned I have a api controller as well for your reference I am sharing the same here. Would request you to please refer the same and suggest.

    Sharing the employee controller here for reference.

    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Http;
    using WebApplication2Test.Database;
    using WebApplication2Test.Models;
    namespace WebApplication2Test.Controllers
    {
        public class EmployeesController : ApiController
        {
           
            public IHttpActionResult GetAllEmployees()
            {
                IEnumerable<EmployeeViewModel> employees = new List<EmployeeViewModel>();
                using (var ctx = new EmployeeDbEntities())
                {
                    var emps = ctx.Employees.ToList();
                    var emptemp = new List<EmployeeViewModel>();
                    foreach (var item in emps)
                    {
                        emptemp.Add(new EmployeeViewModel()
                        {
                            ID = item.ID,
                            Name = item.Name,

                        });
                    }
                    employees = emptemp;
                    //Employees = ctx.Employees.Include("EmployeeAddress").Select(s => new EmployeeViewModel()
                    //{
                    //    Id = s.ID,
                    //    Name = s.Name,
                    //    //Address = s.EmployeeAddress == null || includeAddress == false ? null : new AddressViewModel()
                    //   // {
                    //        // Id = s.EmployeeID,
                    //        // }
                    //    }).ToList<EmployeeViewModel>();
                }
                if (employees.Count() == 0)
                {
                    return NotFound();
                }
                return Ok(employees);
            }
            public IHttpActionResult GetAllEmployees(int id)
            {
                EmployeeViewModel employees = null;
                using (var ctx = new EmployeeDbEntities())
                {
                    var emp = ctx.Employees.Where(w => w.ID == id).Select(s => s).FirstOrDefault();
                    if (emp != null)
                    {
                        employees = new EmployeeViewModel()
                        {
                            ID = emp.ID,
                            Name = emp.Name
                        };
                    }
                    //Employees = ctx.Employees.Include("EmployeeAddress").Select(s => new EmployeeViewModel()
                    //{
                    //    Id = s.ID,
                    //    Name = s.Name,
                    //    //Address = s.EmployeeAddress == null || includeAddress == false ? null : new AddressViewModel()
                    //   // {
                    //        // Id = s.EmployeeID,
                    //        // }
                    //    }).ToList<EmployeeViewModel>();
                }
                if (employees == null)
                {
                    return NotFound();
                }
                return Ok(employees);
            }
            [HttpPost]
            [Route("api/employees/createemployee")]
            public IHttpActionResult CreateEmployee([FromBody]EmployeeViewModel employee)
            {
                if (!ModelState.IsValid)
                    return BadRequest("Not a valid data");
                using (var ctx = new EmployeeDbEntities())
                {
                    ctx.Employees.Add(new Employee()
                    {
                        
                        Name = employee.Name,
                    });
                    ctx.SaveChanges();
                }
                return Ok();
            }
            [HttpPut]
            [Route("api/employees/updateemployee")]
            public IHttpActionResult UpdateEmployee([FromBody]EmployeeViewModel Employee)
            {
                if (!ModelState.IsValid)
                    return BadRequest("Not a valid data");
                using (var ctx = new EmployeeDbEntities())
                {
                    var existingEmployee = ctx.Employees.Where(s => s.ID == Employee.ID).FirstOrDefault<Employee>();
                    if (existingEmployee != null)
                    {
                        existingEmployee.Name = Employee.Name;
                        ctx.SaveChanges();
                    }
                    else
                    {
                        return NotFound();
                    }
                }
                return Ok();
            }
            [HttpDelete]
            [Route("api/employees/Deleteemployee")]
            public IHttpActionResult Delete(int id)
            {
                if (id <= 0)
                    return BadRequest("Not a valid Employee id");
                using (var ctx = new EmployeeDbEntities())
                {
                    var Employee = ctx.Employees
                        .Where(s => s.ID == id)
                        .FirstOrDefault();
                    ctx.Entry(Employee).State = System.Data.Entity.EntityState.Deleted;
                    ctx.SaveChanges();
                }
                return Ok();
            }
        }
    }

    • Edited by _RJ_ Wednesday, December 4, 2019 11:39 AM deleted the commented section.
    Wednesday, December 4, 2019 11:37 AM
  • With this EmployeesController, your calls using Post and Put should succeed if you use the correct URL as indicated in "Route", and if the JSON in the Body matches correctly the structure of EmployeeViewModel. Be careful with this, the slightest mistake in the JSON will cause the employee to be received as null, and this will produce an error in your code.

    Your Delete method is missing the id in the Route:

    [Route("api/employees/Deleteemployee/{id}")]

    Wednesday, December 4, 2019 3:20 PM
  • Please check if my request message is ok or not: 

    post request url: https://localhost:44316/api/Employees/

    post message body: 

    [
        {
            "name": "Ramesh",
            "isComplete": true
        }
    ]

    Post message response: 

    {
      "message""The requested resource does not support http method 'POST'."

    }

    status : 405Method Not Allowed

    Thursday, December 5, 2019 8:44 AM
  • Please check if my request message is ok or not

    No, this is not Ok. You are calling "https://localhost:44316/api/Employees/". But according to your [Route] attribute, the Url for the POST method should be "https://localhost:44316/api/employees/createemployee".

    Thursday, December 5, 2019 9:25 AM
  • Could you please confirm if my post message syntax is correct or not:

    post message body: 

    [
        {
            "name": "Test6",
            "isComplete": true
        }
    ]

    Thursday, December 5, 2019 9:43 AM
  • It has to match the definition of your class EmployeeViewModel. But this class is not visible anywhere in the code samples that you provided, so we cannot determine whether the JSON in your message body matches the definition of class EmployeeViewModel.
    Thursday, December 5, 2019 12:59 PM
  • Hi, 

    Please find the model class defined:

    using System;

    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    namespace WebApplication2Test.Models
    {
       
        public class EmployeeViewModel
        {
            public int ID { get; set; }
            public string Name { get; set; }
           
        }
        public class StandardViewModel
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public ICollection<EmployeeViewModel> Employees { get; set; }
        }
        public class AddressViewModel
        {
            public int Id { get; set; }
          
        }
    }

    Thursday, December 5, 2019 6:08 PM
  • Ah, no. Given this class, your JSON is not correct.

    Your JSON starts with [ and ends with ]. This means that you are sending an array. But the EmployeeViewModel class does not inherit from List<> or otherwise represent an array.

    To send a single employee, the JSON would look like this:

        {
            "ID": 12345,
            "Name": "Test6"
        }

    The opening and closing {} mean that you are sending an object. Then you get an entry for each property of the object, which for the class EmployeeViewModel happen to be ID and Name (case sensitive!), not name and IsComplete as you had specified. Finally, note how the value for Name is enclosed in quotes because it is a string, but ID does not have quotes because it is an int.

    • Marked as answer by _RJ_ Friday, December 6, 2019 5:07 PM
    Thursday, December 5, 2019 9:23 PM
  • thank you for guidance and assistance.

    all the methods are working and responsive.

    Friday, December 6, 2019 5:08 PM