首页 > 解决方案 > 接受 Text/Plain 格式,就像它是 JSON 一样,以便可以解析模型

问题描述

我有一个 API 将特定类型作为输入,但前端发送请求text/plain而不是application/json.

我怎样才能使 API 自动接受数据,就好像它是 JSON 一样?

[Route("GetNotification")]
[HttpPost]
public IActionResult GetAllNotifications([FromBody]GetNotificationsBySearchVm Search)
{
    try
    {
        GetAllNotificationsVm result = notificationBusiness.GetAllNotification(Search);

         return Ok(result);                
    }
    catch (Exception ex)
    {
        return StatusCode(500, ex.Message);
    }
}

这是请求的正文text/plain

{
    "index":1 ,
    "size": 10,
    "userID":26,
    "appID": null
}

运行时,我收到此错误:

InvalidCastException:无法将类型的对象转换System.String为类型xxx.GetNotificationsBySearchVm

标签: c#asp.net-core

解决方案


推荐阅读