【问题标题】:Getting the response of Asynchronous http web request using POST method in asp.net core在 asp.net core 中使用 POST 方法获取异步 http web 请求的响应
【发布时间】:2017-04-13 07:28:23
【问题描述】:

我正在使用 asp.net 核心。我能够使用 GET 方法从 http webrequest 获得响应。使用 POST 通过 http webrequest 获取响应,我面临 405 错误。(找不到远程服务器) 这是我使用 GET 方法的代码。

 public static void Main(string[] args)
        {
            var task = MakeAsyncRequest("http://localhost:8080/nifi-api/flow/status", "text/html");

            Console.ReadLine();
        }
        public static Task<string> MakeAsyncRequest(string url, string contentType)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = contentType;
            request.Method = "GET";
            request.Proxy = null;

            Task<WebResponse> task = Task.Factory.FromAsync(
                request.BeginGetResponse,
                asyncResult => request.EndGetResponse(asyncResult),
                (object)null);

            return task.ContinueWith(t => ReadStreamFromResponse(t.Result));
        }

        private static string ReadStreamFromResponse(WebResponse response)
        {
            using (Stream responseStream = response.GetResponseStream())
            using (StreamReader reader = new StreamReader(responseStream))
            {
                string results = reader.ReadToEnd();
                if (!string.IsNullOrEmpty(results))
                {
                    Data data = new Data();
                   data = JsonConvert.DeserializeObject<Data>(results);
                }
                return results;
            }
        }

请告诉我如何在 asp.net 核心中使用异步 POST 方法获取响应。提前致谢。

【问题讨论】:

标签: c# rest post asp.net-core


【解决方案1】:

也许是这样?

HttpClient httpClient = new HttpClient();
var response = await httpClient.PostAsync("http://localhost:8080/nifi-api/flow/status", new StringContent("Json string", Encoding.UTF8, "application/json"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    相关资源
    最近更新 更多