【问题标题】:How can I call a url from c# code如何从 c# 代码中调用 url
【发布时间】:2014-04-07 15:13:07
【问题描述】:

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

"/api/MemberApi"

我不需要从服务器返回任何东西。它只需要被调用,Web API 方法就会执行一些代码。虽然如果调用成功了记录一下就好了。

【问题讨论】:

  • 您可以使用HttpWebRequestHttpWebResponse,它们通常用于进行任何Web 服务调用。我无权访问 VS,所以不能举个例子。检查这个link

标签: asp.net asp.net-mvc-4 asp.net-web-api


【解决方案1】:

使用HttpWebRequest

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

使用响应来查看它是否成功。有几个例外可以引发 (http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse(v=vs.110).aspx),这会告诉你为什么你的电话失败了。

【讨论】:

    【解决方案2】:

    WebClient 类是你所需要的。

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

    Example of using WebClient in a console app

    MSDN Documentation

    如果您需要处理低级别的抽象,您也可以使用 HttpWebRequest,但 WebClient 是构建在 HttpWebRequest 之上的更高级别的抽象,以简化最常见的任务。

    【讨论】:

    • @Black 自 c# 3.0 于 2007 年发布
    • 不应该包裹在using子句中吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    • 2012-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多