【发布时间】:2022-02-14 06:31:33
【问题描述】:
使用 Telegram.Bot 包在 ASP.NET Core Web API 中开发 Telegram bot 时如何正确反序列化 POST 方法“Update”? 我使用 DeserializeObject(string) 方法这样做,但它一直返回错误:Newtonsoft.Json.JsonReaderException:解析值时遇到意外字符
代码:
using Microsoft.AspNetCore.Mvc;
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.ReplyMarkups;
using Newtonsoft.Json;
namespace OfficeBooking.TelegramApi.Controllers
{
[ApiController]
[Route(template: "api/message")]
public class TelegramBotController : ControllerBase
{
private readonly TelegramBotClient _telegramBotClient;
public TelegramBotController(TelegramBot telegramBot)
{
_telegramBotClient = telegramBot.GetBot().Result;
}
[HttpPost]
public async Task <IActionResult> Update([FromBody]object update)
{
var upd = JsonConvert.DeserializeObject<Update>(update.ToString());
var chat = upd.Message?.Chat;
if (chat == null)
{
return Ok();
}
await _telegramBotClient.SendTextMessageAsync(
chatId: chat.Id,
text: "Testing sendMessage method",
parseMode: ParseMode.MarkdownV2,
disableNotification: false,
replyMarkup: new InlineKeyboardMarkup(
InlineKeyboardButton.WithUrl(
"Check sendMessage method",
"https://core.telegram.org/bots/api#sendmessage")));
return Ok();
}
}
}
【问题讨论】:
-
你有没有调试过代码,发现
update.ToString()的值是什么?有什么理由你不只是将参数声明为[FromBody] Update upd(而是在方法体中反序列化它)? -
谢谢,帮了大忙。
标签: c# asp.net-core asp.net-web-api json.net json-deserialization