我有一个WebRequest,我正在通过Windows CE项目执行。我能够通过正确的方式发送它,我能够看到它正在击中我的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 :(得分:0)
在创建HttpWebRequest对象时尝试使用Cast,如下例所示:
HttpWebRequest req =
(HttpWebRequest)WebRequest.Create((uploadUrl.ToString());
还将以下属性添加到HttpWebRequest对象
req.Timeout = yourWebRequestTimeoutLimit
req.KeepAlive = False
req.Accept = "application/json"
req.Credentials = New NetworkCredential(userName, password)