GithubHelp home page GithubHelp logo

wallsmedia / dotnet.restapi.client Goto Github PK

View Code? Open in Web Editor NEW
6.0 3.0 4.0 54 KB

Dot Net Core Simple Rest Web API Client

License: Apache License 2.0

C# 100.00%
dotnet ihttpclientfactory rest-api http-client

dotnet.restapi.client's Introduction

Dot Net Core Rest Web Api Client

The convenient Web Rest Api Client for the Rest Web Service at the Docker Container.

Version 3.1.0

  • Add support of .Net Core 3.1
  • Add support of .Net Standard 2.1

Version 3.0.0

  • Add support of .Net Core 3.0
  • Add support of .Net Standard 2.1

Version 2.4.0

  • Add support of IHttpClientFactory
  • Add support of IHttpClientFactory

Nuget Package:

https://www.nuget.org/packages/DotNet.RestApi.Client/

Example of using with IHttpClientFactory ASP.NET Core

Last Release Version 3.1.0 Working samples - https://github.com/Wallsmedia/DotNet.RestApi.Client/tree/master/sample

Add to the configuration initialization:

  public void ConfigureServices(IServiceCollection services)
  {
  ...
        services.AddHttpClient<RestApiClient>();
  }
Using "Polly"
  public void ConfigureServices(IServiceCollection services)
  {
  ...
     //services.AddTransient<RestApiClient>();
     services.AddHttpClient<RestApiClient>().AddTransientHttpErrorPolicy(p => p.RetryAsync(3, onRetry: (res, count) =>
     {
         // for debug demo messaging
         Console.WriteLine($" Exception:{res.Exception.Message} count: {count}");
     }));
  }

For more details of using Polly use link below:

In the controller:

    private RestApiClient _restApiClient;

    /// <summary>
    /// Constructs the class.
    /// </summary>
    /// <param name="configuration">The capture processor configuration.</param>
    /// <param name="logFactory">The logger factory.</param>
    public MarketCaptureController(RestApiClient restApiClient,
        MarketCaptureProcessorServiceConfiguration configuration,
        ILoggerFactory logFactory)
    {
        _restApiClient = restApiClient;
        restApiClient.ConfigureHttpRequstMessage = RestApiClientExtensions.ApplyAcceptEncodingSettingGZip;

        Configuration = configuration;
        _logFactory = logFactory;
        _logInfo = _logFactory?.CreateLogger(Assembly.GetExecutingAssembly().GetName().Name);

    }

    private void GetBitCoinRate(object state)
    {

        try
        {
            Uri baseUri = new Uri(Configuration.BitCoinRequestUrl);
            baseUri = new Uri("https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=EUR");
            var response = _restApiClient.SendJsonRequest(HttpMethod.Get, baseUri, null).GetAwaiter().GetResult();
            var bitcoin = response.DeseriaseJsonResponseAsync<TickerBitcoin[]>().GetAwaiter().GetResult();
            LastMarketTop = bitcoin[0];
            LogMessageResources.TraceBitCoinPrice(_logInfo, bitcoin[0].LastUpdatedUTC, bitcoin[0].price_eur, null);
        }
        catch (Exception e)
        {
            LogMessageResources.OperationException(_logInfo, nameof(MarketCaptureProcessor), e);
        }
    }

Example how to call with JSON:

Uri baseUri = new Uri("http://webServiceHost:15002");
RestApiClient client = new RestApiClient(baseUri);

PurchaseOrder sendObj = new PurchaseOrder();

HttpResponseMessage response = client.SendJsonRequest(HttpMethod.Post, new Uri("res", UriKind.Relative), sendObj).Result;

PurchaseOrder respObj = response.DeseriaseJsonResponse<PurchaseOrder>();

Example how to call with XML:

Uri baseUri = new Uri("http://webServiceHost:15002");
RestApiClient client = new RestApiClient(baseUri, request =>
   {
      request.Headers.Add("CustomHeader", "CustomHeaderValue");
   });

PurchaseOrder sendObj = new PurchaseOrder();

Uri relUri = new Uri(RequestPathAttribute.GetRestApiPath(sendObj), UriKind.Relative);
HttpResponseMessage response = client.SendJsonRequest(HttpMethod.Post, relUri, sendObj).Result;

PurchaseOrder respObj = response.DeseriaseXmlResponse<PurchaseOrder>();

Example how to call with using gzip:

Uri baseUri = new Uri("http://webServiceHost:15002");
RestApiClient client = new RestApiClient(baseUri, request =>
   {
      request.Headers.Add("CustomHeader", "CustomHeaderValue");
      RestApiClientExtensions.ApplyAcceptEncodingSettingGZip(request);
   });

PurchaseOrder sendObj = new PurchaseOrder();

HttpResponseMessage response = client.SendXmlRequest(HttpMethod.Post, new Uri("res", UriKind.Relative), sendObj).Result;

PurchaseOrder respObj = response.DeseriaseXmlResponse<PurchaseOrder>();

Where Web Service should have:

 public void ConfigureServices(IServiceCollection services)
 {
 ...
     services.AddResponseCompression();
 ...
 }
 public void Configure(IApplicationBuilder app)
 {
 ...
     app.UseResponseCompression();
 ...
 }

Example how to call with Data Contract XML:

Uri baseUri = new Uri("http://webServiceHost:15002");
RestApiClient client = new RestApiClient(baseUri);

PurchaseOrder sendObj = new PurchaseOrder();
Uri relUri = new Uri(RequestPathAttribute.GetRestApiPath(sendObj), UriKind.Relative);
HttpResponseMessage response = client.SendJsonRequest(HttpMethod.Post, relUri, sendObj).Result;

PurchaseOrder respObj = response.DeseriaseDcXmlResponse<PurchaseOrder>();

Where the Models:

   [DataContract (Namespace ="http://purchase.Interface.org/Purchase.Order")]
   [RequestPath("add/purchase/order")]
   public class PurchaseOrder
    {
        public PurchaseOrder()
        {
            billTo = new Address() { street = "Bill to Address" };
            shipTo = new Address() { street = "Ship to  Address" };
        }
        [DataMember]
        public Address billTo;
        [DataMember]
        public Address shipTo;
    }


    [DataContract(Namespace = "http://purchase.Interface.org/Purchase.Order.Address")]
    public class Address
    {
        [DataMember]
        public string street;
    }

dotnet.restapi.client's People

Contributors

alexpaskhin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.