Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET WebAPI throw 404 if method parameter is string or int

I did a very simple test on ASP.NET MVC4 WebAPI and found some interesting issue:

When a method is taking complex type, it will work, but when it takes string or int, it will throw 404, as the screen shot given: The "AddProduct" works, but "Test" and "Test1" is always not found.

How should I invoke the method correctly?

Web API Code

404 when invoking the Test method

my route config

like image 516
Edi Wang Avatar asked Nov 29 '12 12:11

Edi Wang


People also ask

How does Web API handle 404 error?

A simple solution is to check for the HTTP status code 404 in the response. If found, you can redirect the control to a page that exists. The following code snippet illustrates how you can write the necessary code in the Configure method of the Startup class to redirect to the home page if a 404 error has occurred.

Can we use Frombody in Httpget?

A Get does not send the body of the form, it only requests a URL. Use a <form> in your view and post it to your controller method, which needs to be decorated with HttpPost.

What is IHttpActionResult C#?

IHttpActionResult contains a single method, ExecuteAsync, which asynchronously creates an HttpResponseMessage instance. C# Copy. public interface IHttpActionResult { Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken); }


1 Answers

You need to decorate your string or int parameter with the [FromBody] attribute.

[HttpPost] public string Test([FromBody]string username)

[HttpPost] public int Test1([FromBody]int value)

like image 168
mr beard Avatar answered Nov 04 '22 07:11

mr beard