Reputation: 41
I have no idea what's going on here. I have a POST route using ASP.NET web API that should change some data in my SQL Server. When I use Postman to test out my REST API it works and the data is changed in the database and the response is okay. But once I use Angular5 to post json to the same database it responds with error 405. Here is my code...
First, here is the POST route from my MVC app.
// POST api/<controller>
[Route("")]
[HttpPost]
public HttpResponseMessage Post([FromBody]BranchesInfo data)
{
BranchesDB.updateBranchRow(data);
var response = Request.CreateResponse<BranchesInfo>(HttpStatusCode.OK,data);
return response;
}
The response from Postman is in the next image. The data is successfully changed in the database although it has no correlation to the info being sent in as my Stored Procedure that's called in the updateBranchRow() function does not respond with any resource, so I made up the resource to return the same data passed in.
Here you can see that the request is recieved and works successfully in PostMan
Now, here is my Angular code which uses a service to post the data.
host: string = "http://localhost:57440/api/branches";
updateBranch(branchKey: Number, mainBranch: String, branchRegion: String, mainBranchFlag: Boolean) {
var data = {
BranchKey: branchKey,
BranchName: mainBranch,
BranchRegion: branchRegion,
MainBranchFlag: mainBranchFlag
}
return this.http.post(this.host, data).map(res => res.json());
});
And here is an image of the error I am getting on the browser console once I try to log the response recieved.
Response on the browser console:
I really don't understand what I'm doing wrong. How can a REST based request work with Postman but not work when using Angular4??
Upvotes: 3
Views: 11008
Reputation: 1211
In Global.asax.cs file add following code
protected void Application_BeginRequest()
{
if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
{
Response.Flush();
}
}
Upvotes: 8
Reputation: 2136
Postman does not send a XmlHttp Request. With postman you're manually interacting with a site so that you have full control. However in your web application you are making a Cross Origin Request.You need to enable CORS in your Api.
You can read more about CORS in Asp.Net Web API here.
Upvotes: 0