C# REST API Client [closed]

2019-03-08 02:14发布

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.

标签: c# wpf api rest
5条回答
我命由我不由天
2楼-- · 2019-03-08 02:50

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.

查看更多
Juvenile、少年°
3楼-- · 2019-03-08 02:51

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.

查看更多
贪生不怕死
4楼-- · 2019-03-08 03:01

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.

查看更多
我想做一个坏孩纸
5楼-- · 2019-03-08 03:03

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

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

查看更多
男人必须洒脱
6楼-- · 2019-03-08 03:08

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
}
查看更多
登录 后发表回答