0
我正在使用asp.net核心。我能夠使用GET方法從http webrequest獲得響應。要通過http webrequest使用POST得到響應,我需要面對405錯誤(未找到遠程服務器) 這裏是我使用GET方法的代碼。在asp.net核心中使用POST方法獲取異步http web請求的響應
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方法獲得響應。提前致謝。
您可以使用HttpClient類使請求更容易。查看http://stackoverflow.com/q/37750451/2833802 – Set