2016-09-07 60 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)