【发布时间】:2020-10-24 21:05:20
【问题描述】:
我有一个 Azure HTTP 触发器函数,它可以作为浏览器中的 URL 或通过 Postman 令人满意地调用。如何从 C# 调用它?
功能是
public static class FunctionDemo
{
[FunctionName("SayHello")]
public static async Task<IActionResult> SayHello(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function 'SayHello' processed a request.");
return new OkObjectResult("Hello world");
}
}
我使用它的代码是
private void button1_Click(object sender, EventArgs e)
{
String url = "https://<app-name>.azurewebsites.net/api/SayHello";
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string reply = reader.ReadToEnd();
label1.Text = reply;
dataStream.Close();
}
request.GetResponse() 调用失败,Visual Studio 报告:
System.Net.WebException - The underlying connection was closed: An unexpected error occurred on a send.
Inner Exception 1:
IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
Inner Exception 2:
SocketException: An existing connection was forcibly closed by the remote host
【问题讨论】:
-
不要使用
WebRequest,它又旧又破。请改用HttpClient。