C#+GoEasy實現Web實時消息后台服務器推送


第一步:appsettings.json配置GoEasy所需參數

"GoEasy": {
    "URL": "https://rest-hangzhou.goeasy.io/publish",
    "Appkey": "BC-**************************"
  }

第二步:添加GoEasy發送消息公共方法

using Dw.Util.Helper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace Dw.BLL.Other
{
    /// <summary>
    /// GoEasy相關方法
    /// </summary>
    public class Other_GoEasyBLL
    {
        string message = "";

        #region 發送消息
        /// <summary>
        /// 發送消息
        /// </summary>
        /// <param name="channel">channel</param>
        /// <param name="content">您要發送的消息內容</param>
        /// <returns></returns>
        public string SendMessage(string channel,string content)
        {
            try
            {
                string postDataStr = "appkey="+ ConfigHelper.GetValue("GoEasy:Appkey") + "&channel=" + channel + "&content=" + content;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ConfigHelper.GetValue("GoEasy:URL"));
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
                request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
                Stream myRequestStream = request.GetRequestStream();
                byte[] data = Encoding.UTF8.GetBytes(postDataStr);
                myRequestStream.Write(data, 0, data.Length);

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                message = "success";
            }
            catch (Exception ex)
            {
                message = ex.Message.ToString();
                throw;
            }
            return message;
        }
        #endregion
    }
}

第三步:接口測試

  #region GoEasy實現聊天
        /// <summary>
        /// GoEasy實現聊天
        /// </summary>
        /// <returns></returns>
        [Route("GoEasySendMessage")]
        [HttpGet]
        public ActionResult GoEasySendMessage(string content)
        {
            string msg = other_GoEasyBLL.SendMessage("my_channel",content);
            if(msg== "success")
            {
                return Ok(new { code = "200", res = new { msg = "發送成功!" } });
            }
            return Ok(new { code = "400", res = new { msg = msg} });
        }
        #endregion

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM