2016-09-07 3 views
0

У меня есть WebRequest, который я выполняю через проект Windows CE. Я могу отправить его правильно, и я могу видеть, что он поражает мой WebApi. Единственная проблема заключается в том, что при прохождении запроса параметр всегда равен нулю.WebRequest POST json параметр, показывающий как Null на WebAPI

Web API

[Route("")] 
    public IHttpActionResult Post([FromBody] StopInfo stopInfo) 
    { 
     try 
     { 
      _scannerService.AddStops(stopInfo); 
      return Ok(stopInfo); 

     } 
     catch (Exception ex) 
     { 
      //return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); 
      return null; 
     } 
    } 

WebRequest

private void btnUpload_Click(object sender, EventArgs e) 
    { 

     StopInfo s1 = new StopInfo(); 
     s1.ContactName = "Test"; 
     s1.CompanyName = "Ignite"; 
     s1.City = "Katy"; 
     s1.Addr1 = "22908 Mountain View"; 
     s1.Addr2 = "Suite 300"; 
     s1.State = "TX"; 
     s1.Zip = "77449"; 

     string uploadUrl = txtServerText.Text + "/api/stops"; 

     string json = JsonConvert.SerializeObject(s1); 

     System.Net.WebRequest req = System.Net.WebRequest.Create(uploadUrl); 

     req.ContentType = "application/json"; 
     req.Method = "POST"; 

     byte[] bytes = System.Text.Encoding.ASCII.GetBytes(json); 
     req.ContentLength = bytes.Length; 
     System.IO.Stream os = req.GetRequestStream(); 
     os.Write(bytes, 0, bytes.Length); //Push it out there 
     os.Close(); 
     System.Net.WebResponse resp = req.GetResponse(); 

     System.IO.StreamReader sr = 
       new System.IO.StreamReader(resp.GetResponseStream()); 

    } 

ответ

0

Попробуйте использовать Cast при создании HttpWebRequest объекта, как показано ниже примере:

HttpWebRequest req =  

     (HttpWebRequest)WebRequest.Create((uploadUrl.ToString()); 

Кроме того, добавьте ниже СВОЙСТВ с объекту HttpWebRequest

req.Timeout = yourWebRequestTimeoutLimit 
    req.KeepAlive = False 
    req.Accept = "application/json" 
    req.Credentials = New NetworkCredential(userName, password)