歡迎光臨
每天分享高質量文章

.net core編寫轉發服務

我有個小夥伴問我,他需要寫一個轉發服務的他有很多功能要透過他的服務轉發~

技術棧又不一定asp.net core,我就想起泥水老前輩的BeetleX.FastHttpApi

中午午休,折騰了一會兒前輩,問清楚了FastHttpApi如何配置控制器依賴註入和控制器的路由配置

花了一些時間折騰,算折騰出來了

入口呼叫部分程式碼如下

        static void Main(string[] args)
        {
            UnitWork.Instance.Register((services) =>
            {
                services.AddScoped();

                services.AddSingleton();

                services.AddSingleton(typeof(IConfig), (serviceProvider)=>
                {
                    var instance = new Config();
                    instance.TryAdd("maill");
                    return instance;
                });
            });
            UnitWork.Instance.Builder();

            var mApiServer = new HttpApiServer();
            mApiServer.ActionFactory.ControllerInstance += (o, e) =>
            {
                e.Controller = UnitWork.Instance.ServiceProvider.GetRequiredService(e.Type);
            };
            mApiServer.Register(Assembly.Load("Forward.Core"));
            mApiServer.Open();

            Console.ReadLine();
        }
    }

服務本體

    public class MaillService : IForwardService
    {
        private string userName = "2598145226@qq.com";
        private string pawssword = "********";
        private string _host = "smtp.qq.com";

        [ParamType(typeof(MaillModel))]
        public async Task<object> ExecuteAsync(object param)
        {
            MaillModel maillModel = param as MaillModel;

            using (SmtpClient smtpClient = new SmtpClient(_host, 587))
            {
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定電子郵件傳送方式
                smtpClient.Host = _host;//指定SMTP伺服器
                smtpClient.Credentials = new NetworkCredential(userName, pawssword);//使用者名稱和密碼
                smtpClient.EnableSsl = true;

                MailAddress fromAddress = new MailAddress(userName, "華燈");
                MailAddress toAddress = new MailAddress(maillModel.ToMail);
                MailMessage mailMessage = new MailMessage(fromAddress, toAddress);

                mailMessage.Subject = maillModel.Subject;//主題
                mailMessage.SubjectEncoding = Encoding.UTF8;
                mailMessage.Body = maillModel.Body;//內容
                mailMessage.BodyEncoding = Encoding.UTF8;//正文編碼
                mailMessage.IsBodyHtml = true;//設定為HTML格式
                mailMessage.Priority = MailPriority.Normal;//優先順序

                await smtpClient.SendMailAsync(mailMessage);
            }

            return true;
        }
    }

    internal class MaillModel
    {
        public string ToMail { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }
    }

轉發服務部分

   [Controller(BaseUrl = "/Forward", SingleInstance = false)]
    public class Forward
    {
        private IForwardFactory ForwardFactory { get; }

        public Forward(IForwardFactory forwardFactory)
        {
            ForwardFactory = forwardFactory;
        }

        [Post(Route = "{url}")]
        [NoDataConvert]
        public async Task Service(string url,IHttpContext context)
        {
            var result = new ResponseModel()
            {
                RequestTime = DateTime.Now
            };

            try
            {
                var json = context.Request.Stream.ReadString(context.Request.Length);

                result.Data = await ForwardFactory.ForwardAsync(url, json);
                result.ResponseTime = DateTime.Now;

                result.IsSuccessFul = true;
            }
            catch(Exception ex)
            {
                result.ResponseTime = DateTime.Now;
                result.Data = ex.ToString();
            }

            return result;
        }
    }
   [Controller(BaseUrl = "/Forward", SingleInstance = false)]
    public class Forward
    {
        private IForwardFactory ForwardFactory { get; }

        public Forward(IForwardFactory forwardFactory)
        {
            ForwardFactory = forwardFactory;
        }

        [Post(Route = "{url}")]
        [NoDataConvert]
        public async Task Service(string url,IHttpContext context)
        {
            var result = new ResponseModel()
            {
                RequestTime = DateTime.Now
            };

            try
            {
                var json = context.Request.Stream.ReadString(context.Request.Length);

                result.Data = await ForwardFactory.ForwardAsync(url, json);
                result.ResponseTime = DateTime.Now;

                result.IsSuccessFul = true;
            }
            catch(Exception ex)
            {
                result.ResponseTime = DateTime.Now;
                result.Data = ex.ToString();
            }

            return result;
        }
    }

他只需要在入口地方註入服務即可

呼叫一個傳送郵件的服務

專案在

https://github.com/htrlq/ForwardService

贊(0)

分享創造快樂