如何从c#代码调用url

时间:2022-09-01 16:36:21

How can I call a web api url from a csharp console application.

如何从csharp控制台应用程序调用web api url。

"/api/MemberApi"

I don't need anything back from the server. It just needs to be called and the Web API method will execute some code. Although it would be good to record if the call succeeded.

我不需要从服务器上取回任何东西。它只需要调用,而Web API方法将执行一些代码。尽管如果通话成功,最好记录下来。

2 个解决方案

#1


18  

WebClient class is what you need.

WebClient类是您所需要的。

var client = new WebClient();
var content = client.DownloadString("http://example.com");

Example of using WebClient in a console app

在控制台应用程序中使用WebClient的例子。

MSDN Documentation

MSDN文档

You can also use HttpWebRequest if you need to deal with a low level of abstraction but WebClient is a higher-level abstraction built on top of HttpWebRequest to simplify the most common tasks.

如果需要处理较低层次的抽象,还可以使用HttpWebRequest,但WebClient是构建在HttpWebRequest之上的高级抽象,用于简化最常见的任务。

#2


7  

Use the HttpWebRequest

使用HttpWebRequest

HttpWebRequest request = WebRequest.Create("http://www.url.com/api/Memberapi") as HttpWebRequest;
//optional
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream stream = response.GetResponseStream();

Use the response to see if it was successfull or not. There are several Exceptions that can be raised (http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse(v=vs.110).aspx), which would show you, why your call has failed.

使用响应来查看它是否成功。可以引发几个异常(http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse(v=vs.110).aspx),它将向您展示为什么您的调用失败。

#1


18  

WebClient class is what you need.

WebClient类是您所需要的。

var client = new WebClient();
var content = client.DownloadString("http://example.com");

Example of using WebClient in a console app

在控制台应用程序中使用WebClient的例子。

MSDN Documentation

MSDN文档

You can also use HttpWebRequest if you need to deal with a low level of abstraction but WebClient is a higher-level abstraction built on top of HttpWebRequest to simplify the most common tasks.

如果需要处理较低层次的抽象,还可以使用HttpWebRequest,但WebClient是构建在HttpWebRequest之上的高级抽象,用于简化最常见的任务。

#2


7  

Use the HttpWebRequest

使用HttpWebRequest

HttpWebRequest request = WebRequest.Create("http://www.url.com/api/Memberapi") as HttpWebRequest;
//optional
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream stream = response.GetResponseStream();

Use the response to see if it was successfull or not. There are several Exceptions that can be raised (http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse(v=vs.110).aspx), which would show you, why your call has failed.

使用响应来查看它是否成功。可以引发几个异常(http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse(v=vs.110).aspx),它将向您展示为什么您的调用失败。