20

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

"/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.

2
  • You can use HttpWebRequest and HttpWebResponse which are generally used to make any web service call. I do not have access to VS so cannot give an example. Check this link Commented Mar 5, 2014 at 14:00
  • stackoverflow.com/a/61664627/3596441 Commented Jan 19, 2024 at 18:58

2 Answers 2

37

WebClient class is what you need.

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

Example of using WebClient in a console app

MSDN Documentation

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@Black Since c# 3.0 released in 2007
Shouldn't it be wrapped in a using clause?
9

Use the 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.