I am developing an API in asp.net core mvc for doing online reservations. But when I am trying to add a reservation from the API post method I am getting error:
WebException: The remote server returned an error: (415) Unsupported Media Type. System.Net.HttpWebRequest.GetResponse()
There are 2 projects:
Project 1
There is a post method in my API action method that a [FromBody] attribute. I have to call this method and pass the reservation object.
The method definition is :
[HttpPost]
public Reservation Post([FromBody] Reservation res) =>
repository.AddReservation(new Reservation
{
Name = res.Name,
FromLocation = res.FromLocation,
ToLocation = res.ToLocation
});
Project 2 In project 2 I want to call this API method. For that I have created a form in the view to fill name, from location and to location values. Then On the controller I have to call the API method (given above).
The controller code is:
[HttpPost]
public IActionResult AddReservation(Reservation reservation)
{
HttpWebRequest apiRequest = WebRequest.Create("http://localhost:8888/api/Reservation") as HttpWebRequest;
apiRequest.Method = "Post";
string parameters = "Name=" + reservation.Name + "Image=" + reservation.Image + "&FromLocation=" + reservation.FromLocation + "&ToLocation=" + reservation.ToLocation;
byte[] byteArray = Encoding.UTF8.GetBytes(parameters);
apiRequest.ContentType = "application/x-www-form-urlencoded";
apiRequest.ContentLength = byteArray.Length;
// Add the post data to the web request
Stream postStream = apiRequest.GetRequestStream();
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
string apiResponse = "";
using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
apiResponse = reader.ReadToEnd();
}
return RedirectToAction("Index");
}
I am getting error - WebException: The remote server returned an error: (415) Unsupported Media Type. System.Net.HttpWebRequest.GetResponse()
But when I am running powershell command then it works:
PM> Invoke-RestMethod http://localhost:8888/api/Reservation -Method POST -Body (@{Name="Anne"; ToLocation="Meeting Room 4"} | ConvertTo-Json) -ContentType "application/json"
Please help?