Home > Software engineering >  Web API Post Parameter Null
Web API Post Parameter Null

Time:10-23

I am new to WEB API and I have created a get and a post method the get is working however the the parameter in the post is returning null.

The code for request is

if (ModelState.IsValid)
        {

            var client = new RestClient(string.Format("{0}/api/order/createorder",Baseurl));
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            var test = JsonConvert.SerializeObject(order);
            request.AddJsonBody(order);
           
            IRestResponse response = client.Execute(request);

and it points to the following method

[HttpPost]
 [Route("api/order/createorder")]
    public HttpResponseMessage AddOrder([FromBody]IOrder order)
    {

        if(order== null)
        {
            var resp = new HttpResponseMessage(HttpStatusCode.BadRequest)
            {
                Content = new StringContent("The order is a required parameter"),
                ReasonPhrase = "Order not present"
            };
            throw new HttpResponseException(resp);
        }

I have added the <requestLimits maxAllowedContentLength="4294967295" /> to the web config but to no avail.

Can anyone point me to what I am doing wrong with the request?

Cheers

CodePudding user response:

I think if can rewrite you request to this ->

var client = new RestClient("/api/order/createorder",Method.Post, DataFormat.Json);
client.AddJsonBody(order);
IRestResponse response = client.Execute(request);

That might just work, you may need some mapping potentially if the payload you are passing to the controller is a different type.

CodePudding user response:

Try this code

var client = new RestClient(string.Format("{0}/api/order/createorder",Baseurl));
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json; charset=utf-8");
var body = JsonConvert.SerializeObject(order);
request.AddParameter("application/json; charset=utf-8", body,  ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var result = response.Content;

and never use interfaces in action parameters, since the action needs to create an object, but it is impossible from interface

[Route("~/api/order/createorder")]
 public HttpResponseMessage AddOrder([FromBody] Order order)
  • Related