lundi 2 avril 2018

What is the best design pattern for Calling 3rd party service in C#

I have a web api & my project is fully dependent with 3rd party services,

  1. connect banks (functions) - Provider 1 (3rd party service), Provider 2(3rd party service)...

  2. payment service(functions) - provider 1(paypal), provider 2(ingenico)...

how to connect the web client with easy manner. What is the Best

Design pattern

to get the faster result & exception handling.

I created simple pattern as below,

  using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Console
{    public class HttpClient
    {        public class HttpGetResponse
        {
            protected Uri RequestUri { get; set; }
            protected string Type { get; set; }
            protected string Httpmethod { get; set; }
            protected string Headers { get; set; }
            protected string AppId { get; set; }
            protected string SecretKey { get; set; }
            protected string RequestBody { get; set; }
            public HttpGetResponse(Uri uri, string Type, string httpmethod, string appId, string secretkey, object requestobject)
            {
                RequestUri = uri;
                this.Type = Type;
                Httpmethod = httpmethod;
                AppId = appId;
                SecretKey = secretkey;
                ReqData reqData = new ReqData() { data = requestobject };
                String providerJson = JsonConvert.SerializeObject(reqData, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore,
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                });
                RequestBody = providerJson;
                Httpmethod = httpmethod;
            }
            public virtual T AsJson<T>() where T : class
            {

                T output = null;
                ResData<T> Res = new ResData<T>();

                var outputstring = GetStreamReader();

                Res = JsonConvert.DeserializeObject<ResData<T>>(outputstring, new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.All
                });

                output = Res.data;

                return output;

            }
            protected virtual string GetStreamReader()
            {
                try
                {
                    HttpWebRequest conn = (HttpWebRequest)WebRequest.Create(this.RequestUri);

                    conn.Method = this.Httpmethod;
                    conn.ContentType = "application/json";
                    if (this.Httpmethod.ToUpper() != "GET")
                    {
                        using (Stream webStream = conn.GetRequestStream())
                        using (StreamWriter requestWriter = new StreamWriter(webStream))
                        {
                            requestWriter.Write(this.RequestBody);
                            requestWriter.Close();
                        }
                    }
                    if (!string.IsNullOrEmpty(AppId))
                    {
                        conn.Headers["App-id"] = AppId;
                        conn.Headers["Secret"] = SecretKey;

                    }

                    WebResponse response = conn.GetResponse();
                    StreamReader sr = new StreamReader(response.GetResponseStream());
                    string result = sr.ReadToEnd();
                    return result;
                }
                catch (WebException ex)
                {
                    string msg = string.Empty;
                    System.IO.Stream st = ((System.Net.HttpWebResponse)(ex.Response)).GetResponseStream();

                    StreamReader sr = new StreamReader(st);
                    string result = sr.ReadToEnd();

                    return result;
                }
            }
            public class ReqData
            {
                public object data;
            }
            public class ReqData<T>
            {
                public T data;
            }
            public class ResData<T>
            {
                private string _error_class = string.Empty;
                private string _error_message = string.Empty;
                private object _request = new object();

                [JsonProperty("error_class")]
                public string Error_class { get => _error_class; set => _error_class = value; }

                [JsonProperty("error_message")]
                public string Error_message { get => _error_message; set => _error_message = value; }

                [JsonProperty("request")]
                public object Request { get => _request; set => _request = value; }

                public T data;
            }
        }
        public static HttpGetResponse Get(Uri uri, string Type, string AppId, string SecretKey, object requestobject)
        {
            return Factory.CreateResponse(uri, Type, "GET", AppId, SecretKey, requestobject);
        }
        public static HttpGetResponseFactory Factory = new HttpGetResponseFactory();
        public class HttpGetResponseFactory
        {
            public virtual HttpGetResponse CreateResponse(Uri uri, string Type, string httpmethod, string AppId, string Secretkey, object requestobject)
            {
                return new HttpGetResponse(uri, Type, httpmethod, AppId, Secretkey, requestobject);
            }
        }
    }
}

Client invoke like,

HttpClient.POST(new Uri(BaseUri, "customers"), "JSON", AppId, Secredkey, Request).AsJson<CustomerResponse>();

Aucun commentaire:

Enregistrer un commentaire