c# - ASP.Net Core 传递 HttpRequestMessage 参数始终为空

标签 c# asp.net-core asp.net-core-webapi

传递的参数有些奇怪。函数正在被调用,我可以调试它,但请求始终为空。

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

网址:https://localhost/api/LineBot

最佳答案

Asp.net core 不再使用 HttpRequestMessageHttpResponseMessage。您需要将 Github 存储库中的代码转换为 WebhookRequestMessageHelper

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

这样它就可以在.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();
}

这是一个简化的示例,不验证签名。

关于c# - ASP.Net Core 传递 HttpRequestMessage 参数始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52885065/

相关文章:

xml - net core 3 AddXmlSerializerFormatters() 配置选项

c# - 在 .NET 中执行 stream.CopyTo(anotherStream) 时如何获得复制百分比?

c# - 设置EF拦截器文件名布局

c# - 根据值更改 DataGrid 单元格颜色

c# - ReSharper - 条件编译 XML 注释错误

c# - 如何将 ASP.NET Core 配置为对两个已部署的应用程序具有不同的配置

c# - 如何将 .xproj 引用到 .csproj 中?

asp.net - Blazor WebSocket 已关闭,状态代码为 1006

angular - 使用 token API 和 angular 进行防伪

c# - 在浏览器中查看 PDF 文档时出错