Pergunta

I am a beginner in web api asp.net MVC and I have a problem. I have a class that I will use in web api HttpGet and HttpPost:

public class Credit
{
public string Log {get; set;}
public string Pas {get; set;}
}

In the example API controller I have:

[HttpGet]
public void Login (Credit credit)
{
}

[HttpPost]
public void Login (Credit credit)
{
}

Tests of these methods in RestConsole in Google Chrome, sending json data:

{"Log", "test", "Pas": "test"}

When debugging these methods, I see that HttpPost is working properly and parameter of "credit" is filled with properties. However HttpGet is not working properly, the object is not filled property, it is NULL. Can someone explain to me this situation and how can I get the complete object in the HttpGet?

Foi útil?

Solução

This is because of how Web API creates parameter values from the HTTP request.

By default, if the parameter is a "complex" type (such as your Credit class), Web API gets the parameter value from the body of the request. If the parameter is a "simple" type (e.g., int or string), then Web API gets the value from the request URI.

However, HTTP GET requests cannot have a request body. So by default you can't pass a complex type to a Web API "GET" method.

You can read more here: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

In any case, for a Login method, you probably should use a POST request, not a GET request.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top