简体   繁体   English

ASP.Net核心传递HttpRequestMessage参数始终为空

[英]ASP.Net Core Passing HttpRequestMessage Parameter always empty

There is something weird with the passing parameter. 传递参数有些奇怪。 The function is being called, I can debug it, but the request is always empty. 正在调用该函数,我可以对其进行调试,但请求始终为空。

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

Is the HttpRequestMessage suppose to get every data from the request? HttpRequestMessage是否假设从请求中获取每个数据?

Some example of calling it: 调用它的一些例子:

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

the url: https://localhost/api/LineBot url: https:// localhost / api / LineBot

Asp.net core no longer uses HttpRequestMessage or HttpResponseMessage . Asp.net核心不再使用HttpRequestMessageHttpResponseMessage you would need to convert the code from the Github Repository for the WebhookRequestMessageHelper 您需要从Github存储库转换WebhookRequestMessageHelper的代码

https://github.com/pierre3/LineMessagingApi/blob/master/Line.Messaging/Webhooks/WebhookRequestMessageHelper.cs https://github.com/pierre3/LineMessagingApi/blob/master/Line.Messaging/Webhooks/WebhookRequestMessageHelper.cs

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

so that it will work in .net core. 这样它才能在.net核心中运行。

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

This is meant to be a simplified example which does not verify signature. 这是一个不验证签名的简化示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM