Answer the question
In order to leave comments, you need to log in
How to differentiate GET/POST methods in controller class?
I study the built-in login controller of the latest Microsoft MVC in particular and client-server interaction in general.
In the examples below, there is no special indication, get or post method, but when debugging, they are clearly aware of who is get and who is not. How is this done based on the input parameters?
public class AccountController : ApiController
{
// GET api/Account/UserInfo
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
[Route("UserInfo")]
public UserInfoViewModel GetUserInfo()
{
ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);
return new UserInfoViewModel
{
Email = User.Identity.GetUserName(),
HasRegistered = externalLogin == null,
LoginProvider = externalLogin != null ? externalLogin.LoginProvider : null
};
}
// POST api/Account/Logout
[Route("Logout")]
public IHttpActionResult Logout()
{
Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);
return Ok();
}
}
Answer the question
In order to leave comments, you need to log in
It is possible through the parameters of the Request object. There is such a field. However, this is bad practice. I would recommend overloading the method with some parameter (it's unlikely that you are doing a POST without parameters) and setting the [httpget][httppost] attributes.
And about the code above - there requests are made to different addresses. In the same place, a POST request is not made to api / Account / and the system itself guesses what needs to be done Logout
There are several ways to determine what types of requests a particular method handles. One method can only process requests of one type (for example, only GET, or only POST). Personally, I prefer to put a special attribute like [HttpGet] before the method, which, together with [Route("custom/url/for/method")] and a clear method name, makes the controller code as clear as possible. In addition to attributes, the web api also supports the naming convention method for determining what type of requests the method processes. I don't remember the details, you have to read the doc . Well, as in your example, the controller understands that the logout accepts only post requests - I have no idea, you also need to go into the documentation for this, such fine points are described in detail there.
Well, in general, no offense is said, it is better to immediately look for answers to questions of such a plan in the documentation.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question