简体   繁体   中英

Web API Post Parameter Null

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

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.

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)

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