使用WebClient进行POST时使用WebRequest,HttpClient

时间:2017-08-31 12:22:15

标签: c# asp.net json asp.net-web-api webclient

我开发了一个具有以下Action

的Web API 2应用程序
[Route("submit")]
        [HttpPost]
        public async Task<IHttpActionResult> Submit([FromBody]Request request)
        {
            if (request != null)
            {
                try
                {
                    //Do Something
                }
                catch (Exception ex)
                {
                    return this.InternalServerError(ex);
                }
            }
            else
            {
                return this.BadRequest("Request is null");
            }
        }

在我的客户端应用程序中,如果我使用WebClient来调用此操作,则操作中的请求对象将变为null。

使用WebClient - 无法正常工作

private static void CallWebAPIUsingWebClient(string dataString, TokenResponse token, string url)
        {            
            using (WebClient client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                client.Headers[HttpRequestHeader.Accept] = "application/json";
                client.Headers.Add("Username", "WebClient");
                client.UploadString(url, "POST", dataString);
            }
        }

但是,如果我甚至使用WebRequest或HttpClient,我将在操作中获得完整的请求对象。

使用WebRequest - 工作

private static void CallWebAPIUsingWebRequest(string dataString, TokenResponse token, string url)
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.Accept = "application/json";
            httpWebRequest.ContentType = "application/json";

            httpWebRequest.Method = "POST";
            httpWebRequest.Headers.Add("Username", "WebRequest");

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(dataString);
                streamWriter.Flush();
                streamWriter.Close();
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                string result = streamReader.ReadToEnd();
            }
        }

使用HttpClient - 正常工作

private async static Task CallWebAPIUsingHttpClient(string dataString, TokenResponse token, string url)
        {
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("Username", "HttpClient");
                await client.PostAsync(url, new StringContent(dataString, System.Text.Encoding.UTF8, "application/json"));
            }
        }

奇怪的是,即使WebClient一直工作到昨天。 请让我知道为什么WebClient无效。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

检查您是否在以下方法中使用HTTPPUT,原始api控制器操作方法接受HTTPPOST

private static void CallWebAPIUsingWebClient(string dataString, TokenResponse token, string middlewareUrl)
        {            
            using (WebClient client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                client.Headers[HttpRequestHeader.Accept] = "application/json";
                client.Headers[HttpRequestHeader.Authorization] = token.TokenType.ToLowerInvariant() + " " + token.AccessToken;
                client.Headers.Add("Username", "WebClient");
                client.UploadString(middlewareUrl, "PUT", dataString);
            }
        }