简体   繁体   中英

“Message”: “The requested resource does not support http method 'POST'.” JSON return in .net api

I get this message:

The requested resource does not support http method 'POST'

from Postman when testing my post method:

[HttpPost]
public Reservation AddReservation(string firstname, string lastname, string email, string cardnumber, string phonenumber)
{
    if (!ModelState.IsValid)
    {
        throw new HttpResponseException(HttpStatusCode.BadRequest);
    }

    Reservation res = new Reservation()
            {
                FirstName = firstname,
                LastName = lastname,
                Email = email,
                Cardnumber = cardnumber,
                PhoneNumber = phonenumber
            };

    _context.Reservations.Add(res);
    _context.SaveChanges();

    return res;
}

If I make the post method getting object like this:

[HttpPost]
public Reservation AddReservation(Reservation res)
{
    if (!ModelState.IsValid)
    {
        throw new HttpResponseException(HttpStatusCode.BadRequest);
    }

    _context.Reservations.Add(res);
    _context.SaveChanges();

    return res;
}

then my POST method works correctly, but on the front-end side, I want to pass the parameters, not the model class.

Can someone tell me why this happens?

Thank you very much

We need to change the function to

[HttpPost]
        public IHttpActionResult AddReservation([FromBody] Reservation model)
        { 

            _context.Reservations.Add(model);
            _context.SaveChanges();
            return Json(_context.Reservations.ToArray());
        }

because POST is expecting a parameter - payload in query string. Without this parameter, it is looking for Post() function which is not defined, and we are getting error 405

Reservation.cs
public class Reservation
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Cardnumber { get; set; }
        public string PhoneNumber { get; set; }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM