iT邦幫忙

0

WebHook 怎麼儲存User的step或是參數

  • 分享至 

  • xImage

Update...
有前輩指點,可以使用Session將物件的資料存放在Ram內,但測試後,只有GET取得的到Session值,但Post不行。以下是POST相關程式碼…


前輩們好,之前寫Line 的WebHook,有網路高手董大偉 david Sir,提供下一步下一步的下個階層的功能,這功能很好用
例如:功能選單中User點選請假,我回覆假別清單,點選假別,我回覆可請日期 ....

但最近在寫另一個通訊軟體的WebHook (不是用Line),自己寫Controller一直作不出來

請問這大概要怎麼作呢? 或是有什麼關鍵字可尋嗎? 麻煩了

以下是POST程式碼…

    ---WebApiConfig
    public static class WebApiConfig
    {
        public static string UrlPrefix { get { return "api"; } }
        public static string UrlPrefixRelative { get { return "~/api"; } }

        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: WebApiConfig.UrlPrefix + "/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
    
    ---Controll
    [RoutePrefix("api/test")]
    public class TPController : ApiController
    {
        private string accesstoken = "";
        private string replyApiUrl = "";                

        // GET api/<controller>
        [Route("")]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        protected override void Initialize(HttpControllerContext controllerContext)
        {
            base.Initialize(controllerContext);
        }

        // PUT api/<controller>/5
        public IHttpActionResult Put(int id, [FromBody]string value)
        {
            return Ok("value");
        }

        // DELETE api/<controller>/5
        public IHttpActionResult Delete(int id)
        {
            return Ok("value");
        }

        [Route("")]
        [HttpPost]
        // POST api/<controller>
        public IHttpActionResult Post([FromBody]object value)
        {
            accesstoken = "XXXXX";
            replyApiUrl = @"http://web.com.tw//aaaa/test.ashx";
            ReciveMessage recMsg = new ReciveMessage();
            recMsg = JsonConvert.DeserializeObject<ReciveMessage>(value.ToString());

            var session = System.Web.HttpContext.Current.Session; //宣告Session
            List<UserStep> lstUser = (List<UserStep>)session["Users"];

            UserStep user = new UserStep();
            if (lstUser == null)
            {
                lstUser = new List<UserStep>();
                user.UserID = recMsg.events[0].Source.userId;
                lstUser.Add(user);
            }
            else if (lstUser.Where(a => a.UserID == recMsg.events[0].Source.userId).Count() == 0)
            {
                user.UserID = recMsg.events[0].Source.userId;
                lstUser.Add(user);
            }

            user = lstUser.Where(a => a.UserID == recMsg.events[0].Source.userId).FirstOrDefault();

            foreach (Event eventObj in recMsg.events)
            {
                //建立一個HttpClient物件,用來發出請求
                HttpClient client = new HttpClient();
                //填入token
                client.DefaultRequestHeaders.Add("Authorization", $"{accesstoken}");
                //設定Body的型態
                client.DefaultRequestHeaders
                      .Accept
                      .Add(new MediaTypeWithQualityHeaderValue("application/json"));
                //設定請求的body的Url&請求類型
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, replyApiUrl);

                //判斷事件的類別
                switch (eventObj.type)
                {
                    //如果是訊息事件
                    case "message":
                        switch (eventObj.Message.type)
                        {
                            //如果是文字訊息
                            case "text":
                                //todo 回傳對方傳來的訊息回去
                                ReplyMessage RepMsg = new ReplyMessage();
                                RepMsg.ask = "send";
                                RepMsg.recipient = recMsg.events[0].Source.userId;
                                textMessage message = new textMessage();
                                message.text = string.Format("我收到你的 {0}  訊息了", eventObj.Message.text);

                                RepMsg.message = message;


                                //將回傳訊息的物件放入請求的body
                                string param = JsonConvert.SerializeObject(RepMsg);
                                request.Content = new StringContent(param,
                                                                    Encoding.UTF8,
                                                                    "application/json");
                                //發出請求

                                client.SendAsync(request);
                                break;
                        }
                        break;
                }
            }

            session.Add("Users", lstUser); //將認證資訊放入Session
            return Ok();
        }
    }
    
    
    ---Global.asax
public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
        public override void Init()
        {
            base.Init();
        }

        protected void Application_PostAuthorizeRequest()
        {
            if (IsWebApiRequest())
            {
                HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
            }
        }

        private bool IsWebApiRequest()
        {
            return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(WebApiConfig.UrlPrefixRelative);
        }
    }
看更多先前的討論...收起先前的討論...
天黑 iT邦研究生 5 級 ‧ 2022-02-09 17:29:02 檢舉
blog 文章下方問題,其實有提到如何實作儲存狀態喔
https://studyhost.blogspot.com/2017/08/linebot11chat-bot.html
gtalex iT邦新手 5 級 ‧ 2022-02-10 14:11:09 檢舉
感謝horace_work大大
早上看完後試著使用Session,在GET上可以取得Session值,在POST一直無法。這是有限制嗎?
天黑 iT邦研究生 5 級 ‧ 2022-02-10 16:40:46 檢舉
可能要請你,提供比較完整的程式碼才能確認喔
gtalex iT邦新手 5 級 ‧ 2022-02-11 09:36:22 檢舉
感謝horace_work大大
已將程式碼放上了。請再幫我看了一下是哪邊有錯…麻煩了 謝謝
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答