开发者

C# REST Client Example?

Ive been looking everywhere, and nothing seems to work.

Im trying to connect to my REST (WCF) Service. It works fine in firefox using the following:

http://localhost:1337/WCF.IService.svc/rest/Services?CostCentreNo=1&Filter=1

Where rest is the endpoint address; Services?CostCentreNo=1&Filter=1 is the template with params

Below is the Server contract point.

    [OperationContract]
    [WebGet(UriTemplate = "/Services?CostCentreNo={CostCentreNo}&Filter={Filter}")]
    List<Services> GetServices(Int32 CostCentreNo, Int32 Fi开发者_开发知识库lter);

Can I get a working example of connecting to this please from c#..


Create your own proxy by extending System.ServiceModel.ClientBase<IYourServiceContract>. Each of your methods on the REST service is exposed through the Channel property, so you can then wrap these.

[ServiceContract]
public interface IMyServiceContract
{
    [OperationContract]
    [WebGet(UriTemplate = "/ping")]
    string Ping();
}

public class ProxyClient : ClientBase<IMyServiceContract>, IMyServiceContract
{
    #region Implementation of IMyServiceContract

    public string Ping()
    {
        return Channel.Ping();
    }

    #endregion
}

public class Test
{
    // This assumes you have setup a client endpoint in your .config file
    // that is bound to IMyServiceContract.
    var client = new Client();

    System.Console("Ping replied: " + client.Ping());
}

Unfortunately, this is aimed at WCF consumption and doesn't work perfectly with REST, i.e. it doesn't expose the HTTP headers, which are necessary for a RESTful implementation.


Try this for JSON:

String resonse = String.Empty;
HttpClient client = new HttpClient();

using (HttpResponseMessage httpResponse = client.Get("your_uri"))
{
   response = httpResponse.Content.ReadAsString();
}

This code requires the Microsoft.Http and Microsoft.Http.Extensions dlls from the WCF Rest Toolkit - http://aspnet.codeplex.com/releases/view/24644.


For a generic/dynamic solution with sample source see http://www.nikhilk.net/CSharp-Dynamic-Programming-REST-Services.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜