Let me sketch the situation first:
I have a basic controller which looks like this:
public class SearchRequestController : ApiController
{
public IEnumerable<ObjectA> GetAllRequests() {...}
{}
public IEnumerable<ObjectA> GetLatestRequest() {...}
{}
}
Using the following routing
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
I can easly use the functions as follows
Http://myServer/myvirtualdirectory/api/SearchRequest/GetAllRequests
Http://myServer/myvirtualdirectory/api/SearchRequest/GetLatestRequest
Now i wanted to add the following controller
public class UserController : ApiController
{
public IEnumerable<UserObject> SearchUsersByInput() {...}
}
But the following GET doesn't work
Http://myServer/myvirtualdirectory/api/User/SearchUsersByInput
I'm getting a 405: {"Message":"The requested resource does not support http method 'GET'."}
It works however when I change my function as follows:
public class UserController : ApiController
{
[HttpGet]
public IEnumerable<UserObject> SearchUsersByInput() {...}
}
Question: Could someone explain the origin of this behavior? Have I done something wrong or is there something wrong with my routing?
HTTP is a HyperText Transfer Protocol that is designed to send and receive the data between client and server using web pages. HTTPGET and HTTPPOST attributes encode request parameters as key and value pairs in the HTTP request. The HttpGet protocol and the HttpPost protocol provide backward compatibility.
HTTPGet method is default whereas you need to specify HTTPPost attribute if you are posting data using HTTPPost method. 2. HTTPGet method creates a query string of the name-value pair whereas HTTPPost method passes the name and value pairs in the body of the HTTP request.
Answers. 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.
An action (or action method) is a method on a controller which handles requests. Controllers logically group similar actions together. This aggregation of actions allows common sets of rules, such as routing, caching, and authorization, to be applied collectively. Requests are mapped to actions through routing.
Please refer to the post here
You will see that you can use naming convention (which is why the methods with Get in the name work), or you can explicitly specify the HTTP method for an action by decorating the action with the correct HTTP attribute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With