C# REST API Client [closed]

2019-03-08 02:31发布

问题:

I have successfully created a PHP REST API which resides on my server. I am now looking to create the client-side connection to this via my WPF C# application. I found this but my API requires the API key to be sent via a HTTP header, and I can't see you can do that in this. I also created a PHP REST client using CURL and it was very easy, and was hoping that there would be something built into C# to handle requests to REST services.

If someone could point me in the direction of a tutorial they have seen, or a library somewhere I would be grateful.

Thanks.

回答1:

Take a look at RESTSharp. Very powerful, and easy to use.

Works on all platforms too: Web, Windows, WCF, Monotouch, Windows Phone



回答2:

You can just use HttpWebRequest or WebClient to make web requests like you would have with CURL in your PHP client...

If you need to deal with JSON based responses, JSON.Net is a fantastic library.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://a/rest/uri");
request.Method = "POST";
request.Headers.Add("Authorization: OAuth " + accessToken);
string postData = string.Format("param1=something&param2=something_else");
byte[] data = Encoding.UTF8.GetBytes(postData);

request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "application/json";
request.ContentLength = data.Length;

using (Stream requestStream = request.GetRequestStream())
{
    requestStream.Write(data, 0, data.Length);
}

try
{
    using(WebResponse response = request.GetResponse())
    {
        // Do something with response
    }
}
catch (WebException ex)
{
    // Handle error
}


回答3:

Also you can use HttpClient in .NET 4.5.
If you are usint .NET 4.0, the HttpClient API is available in Microsoft.Net.Http nuget.



回答4:

You might also want to check out Hammock.NET @ http://hammock.codeplex.com/ ; it is a joy to work with. You really don't need WCF in all likelyhood.



回答5:

If your PHP REST API backend is documented with Swagger, e.g. using swagger-php, you can use swagger-codegen to generate the API clients in C#, Java, PHP, Ruby, Python and more using the Swagger spec that describes your PHP backend.



标签: c# wpf api rest