Reputation: 8291
I am working on a simple react + asp.net core application where I want to simply add records to the database (created using entityframework core). There is a very simple form with just a textbox and a button. When clicking the button, I receive the following error:
Error: Request failed with status code 405
I did debugging in runtime, and the Create method in the controller class is not evoked. That is, somehow the axios does not recognize the url provided. Below is the client side code:
class Form extends Component {
state = { rubricName: '' }
handleFormSubmit = (event) => {
event.preventDefault();
axios({
method: 'post',
url: 'api/Rubric/Create',
data: {
title: this.state.rubricName,
},
headers: {
'Content-Type': 'text/plain;charset=utf-8',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,PATCH,OPTIONS',
},
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
Here is the controller api class:
[Route("api/[controller]")]
public class RubricController : Controller
{
RubricDataAccessLayer objRubric = new RubricDataAccessLayer();
[HttpPost]
[Route("api/Rubric/Create")]
public int Create(string title)
{
return objRubric.AddRubric(new Rubric { Title = title });
}
}
Any ideas about why I am having this error?
Upvotes: 1
Views: 2420
Reputation: 9642
You have specified incorrect url in request. If there is only one Route
attribute on controller the url should be
api/Rubric
If you keep both urls the resulting url is combined value of Route
attributes
api/Rubric/api/Rubric/Create
If you want to override action url without combining it with controller one just add leading /
(or ~/
)
[HttpPost]
[Route("/api/Rubric/Create")]
public int Create(string title)
In this case request url should be
api/Rubric/Create
Upvotes: 2