Web Api Post not found, but Get found

This is my DefaultApi configuration:

config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}/{action}", defaults: new { action = "DefaultAction", id = RouteParameter.Optional } ); [ActionName("DefaultAction")] public HttpResponseMessage Get(string id) [ActionName("DefaultAction")] public HttpResponseMessage Post(MyClass obj) 

How GET works, but using POST I get a 404 Not Found error?

Any ideas or suggestions?

Edit:

Client-side JavaScript:

 $.ajax({ type: "POST", url: "@Url.Content("~/api/controllername")", data: args, 200: function (data) { ...... } }); 
+6
source share
2 answers

Once you add {action} to your route, the magic code that uses the method name prefix to define the get / post function does not work.

You need to add the [HttpPost] attribute to your Post(MyClass obj) method Post(MyClass obj) :

 [HttpPost] [ActionName("DefaultAction")] public HttpResponseMessage Post(MyClass obj) { // ... } // equivalent to: [HttpPost] public HttpResponseMessage DefaultAction(MyClass obj) { // ... } 

Note. The above method name can be used to determine the name of the action, so you can simply rename your methods based on the route you are using instead of using the ActionName attribute.

+7
source

I had a similar problem and the solution was to add [FromBody] to the method parameter as follows:

 [HttpPost] public void PostIncreaseViewCounter([FromBody]int id) { } 
+7
source

Source: https://habr.com/ru/post/953951/


All Articles