传递参数有些奇怪。该函数正在被调用,我可以调试它,但是请求始终为空。
[EnableCors("SiteCorsPolicy")]
[ApiController]
[Route("api/[controller]")]
public class LineBotController : ControllerBase
{
private LineMessagingClient _lineMessagingClient;
public LineBotController()
{
_lineMessagingClient = new LineMessagingClient(Config._Configuration["Line:ChannelAccessToken"]);
}
[HttpPost]
public async Task<HttpResponseMessage> Post(HttpRequestMessage request)
{
try
{
var events = await request.GetWebhookEventsAsync(Config._Configuration["Line:ChannelSecret"]);
var app = new LineBotApp(_lineMessagingClient);
await app.RunAsync(events);
}
catch (Exception e)
{
Helpers.Log.Create("ERROR! " + e.Message);
}
return request.CreateResponse(HttpStatusCode.OK);
}
}
HttpRequestMessage是否应该从请求中获取所有数据?
调用它的一些示例:
var data = {
'to': 'xxx',
'messages':[
{
"type": "text",
"text": "Hello, world1"
},
{
"type": "text",
"text": "Hello, world2"
}
]
};
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json',
async: false,
data: JSON.stringify({request: data}),
url: url,
authorization: 'Bearer {Key}',
success: function (success) {
var x = success;
},
error: function (error) {
var x = error;
}
});
答案 0 :(得分:3)
Asp.net核心不再使用HttpRequestMessage
或HttpResponseMessage
。您需要将Github存储库中的代码转换为WebhookRequestMessageHelper
/// <summary>
/// Verify if the request is valid, then returns LINE Webhook events from the request
/// </summary>
/// <param name="request">HttpRequestMessage</param>
/// <param name="channelSecret">ChannelSecret</param>
/// <returns>List of WebhookEvent</returns>
public static async Task<IEnumerable<WebhookEvent>> GetWebhookEventsAsync(this HttpRequestMessage request, string channelSecret)
{
if (request == null) { throw new ArgumentNullException(nameof(request)); }
if (channelSecret == null) { throw new ArgumentNullException(nameof(channelSecret)); }
var content = await request.Content.ReadAsStringAsync();
var xLineSignature = request.Headers.GetValues("X-Line-Signature").FirstOrDefault();
if (string.IsNullOrEmpty(xLineSignature) || !VerifySignature(channelSecret, xLineSignature, content))
{
throw new InvalidSignatureException("Signature validation faild.");
}
return WebhookEventParser.Parse(content);
}
以便它可以在.net core中工作。
[HttpPost]
public async Task<IActionResult> Post([FromBody] string content) {
try {
var events = WebhookEventParser.Parse(content);
var app = new LineBotApp(_lineMessagingClient);
await app.RunAsync(events);
} catch (Exception e) {
Helpers.Log.Create("ERROR! " + e.Message);
}
return Ok();
}
这是一个简化的示例,它不验证签名。