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);
}
}