简体   繁体   中英

Using web API with parameters in JSON with FromUri or FromBody

I am trying to create an example with web api . I want the received parameters in JSON with fromuri or frombody . When I create the client I want to send an object or JSON with the information.

In my web API I have this

[HttpPost]
public IHttpActionResult Post([FromUri]Peticion peticion)
{
     return Ok(peticion);
}

and in my client

Peticion obj = new Peticion();
obj.cliente = 2;
obj.factura = 22;
string DATA = Newtonsoft.Json.JsonConvert.SerializeObject(obj);

var client = new HttpClient();
HttpContent content = new StringContent(DATA, UTF8Encoding.UTF8, "application/json");

HttpResponseMessage message = 
client.PostAsync("http://localhost:57418//api/Deudor/",content).Result;

if (message.IsSuccessStatusCode)
{
   string result = message.Content.ReadAsStringAsync().Result;
}

But I need in my client received the JSON. In the web API I need to receive two parameters (cliente, factura) and in my client I need to received the information of that client (name, invoice etc) in JSON.

I used postman, and received the JSON with the information. But in my client C# I couldn't.

Regardless of using .net core or framework, you can use HttpClient to send Get and Post requests to your API.

POST request:

HttpClient client = new HttpClient();
var content = new StringContent(JsonConvert.SerializeObject(YourObject), Encoding.UTF8, "application/json");
client.PostAsync("your url", content);

Then you can get content [FromBody] You can use Post requests and get parameters from url, but it's better to use get in that case.

Get request:

HttpClient client = new HttpClient();
client.GetAsync("your url/api/controller/id/{id}");

In both cases you need to set your routes for your methods with request types (GET, POST). eg: in the get example above:

[Route("api/[controller]")
public class SomeController
{
  [HttpGet]
  [Route("id/{id}")]
  public someGetMethod(int id){
    //do something with id here...
  }
}

In Web API, if the controller method's parameter is not a "simple" type, it tries to get the value from the body. So I think you want to remove [FromUri] in your Post() parameters because you're actually sending that information in the request body.

Source: https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM