2016-09-07 42 views
0

我有一个WebRequest,我通过Windows CE项目执行。我能够正确地发送它,并且我能够看到它正在击中我的WebApi。唯一的问题是,当请求通过时,参数始终为空。WebRequest POST JSON参数显示为空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

尝试当创建HttpWebRequest对象,像下面的例子中使用投放:

HttpWebRequest req =  

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

还要添加下面propertie s到HttpWebRequest对象

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