ASP.NET Core 2.2 POST操作参数为null

时间:2020-04-21 08:40:36

标签: asp.net-core asp.net-core-mvc

我很难绑定POST数据。这是我的示例,其中一个参数(字符串名称)始终为null。如果我使用[FromBody]属性,则调试日志中会出现异常,但没有消息。

一些客户端代码。

 public async getSheetByName(name: string) {
    const baseUrl = 'Sheet';
    const actionUrl = `${baseUrl}/GetSchemaByName`;
    try {
      const response = await axios.post(
        actionUrl,
        { name },
        {
          headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Content-Type': 'application/json',
          },
        },
      );
      return response.data;
    } catch (error) {
      console.error(error);
      throw error;
    }
  }
}

控制器动作。

       [HttpPost]
        public async Task<IActionResult> GetSchemaByName([FromBody]string name)
        {
            var data = sheetService.GetSheet(name);
            return Ok(data);
        }

请求。

fetch("http://localhost:63762/Sheet/GetSchemaByName", 
{"credentials":"include","headers":{"accept":"application/json, text/plain,*/*",
"accept-language":"pl-PL,pl;q=0.9,en-US;q=0.8,en;q=0.7",
"content-type":"application/json",
"sec-fetch-dest":"empty",
"sec-fetch-mode":"cors",
"sec-fetch-site":"same-origin",
"x-requested-with":"XMLHttpRequest"},
"referrer":"http://localhost:63762/",
"referrerPolicy":"no-referrer-when-downgrade",
"body":"{\"name\":\"PiecCO\"}","method":"POST","mode":"cors"});

使用[FromBody]调试日志。

Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Route matched with {action = "GetSchemaByName", controller = "Sheet"}. Executing controller action with signature System.Threading.Tasks.Task`1[Microsoft.AspNetCore.Mvc.IActionResult] GetSchemaByName(System.String) on controller UI.Controllers.SheetController (UI).
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Information: Authorization was successful.
Microsoft.EntityFrameworkCore.Infrastructure:Information: Entity Framework Core 2.2.6-servicing-10079 initialized 'ApplicationContext' using provider 'Microsoft.EntityFrameworkCore.InMemory' with options: StoreName=WebApp 
Exception thrown: 'Newtonsoft.Json.JsonReaderException' in Newtonsoft.Json.dll
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executing action method UI.Controllers.SheetController.GetSchemaByName (UI) - Validation state: Invalid
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action method UI.Controllers.SheetController.GetSchemaByName (UI), returned result Microsoft.AspNetCore.Mvc.OkObjectResult in 9.931ms.
Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor:Information: Executing ObjectResult, writing value of type 'null'.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action UI.Controllers.SheetController.GetSchemaByName (UI) in 117.4553ms

没有[FromBody]的调试日志。

Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 POST http://localhost:63762/Sheet/GetSchemaByName application/json 23
Microsoft.AspNetCore.Routing.EndpointMiddleware:Information: Executing endpoint 'UI.Controllers.SheetController.GetSchemaByName (UI)'
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Route matched with {action = "GetSchemaByName", controller = "Sheet"}. Executing controller action with signature System.Threading.Tasks.Task`1[Microsoft.AspNetCore.Mvc.IActionResult] GetSchemaByName(System.String) on controller UI.Controllers.SheetController (UI).
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Information: Authorization was successful.
Microsoft.EntityFrameworkCore.Infrastructure:Information: Entity Framework Core 2.2.6-servicing-10079 initialized 'ApplicationContext' using provider 'Microsoft.EntityFrameworkCore.InMemory' with options: StoreName=WebApp 
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executing action method UI.Controllers.SheetController.GetSchemaByName (UI) - Validation state: Valid
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action method UI.Controllers.SheetController.GetSchemaByName (UI), returned result Microsoft.AspNetCore.Mvc.OkObjectResult in 5.0369ms.
Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor:Information: Executing ObjectResult, writing value of type 'null'.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action UI.Controllers.SheetController.GetSchemaByName (UI) in 22.7878ms
Microsoft.AspNetCore.Routing.EndpointMiddleware:Information: Executed endpoint 'UI.Controllers.SheetController.GetSchemaByName (UI)'
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 46.8482ms 204 

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。我创建了类并将其作为操作的参数传递。

以下示例。仍然不知道为什么解析单个参数失败。我尝试传递{“ name”:“ someName”},并且不带方括号-仅“ someName”。它没有用。在ModelState对象中总会出现错误消息:

解析值{时遇到

意外字符。路径“,行 1,位置1。

或者当我传递值(someName)时

解析值s时遇到

意外字符。路径“,行 1,位置1。

  [HttpPost]
        public async Task<IActionResult> GetSchemaByName([FromBody]Schema schema)
        {
            var data = sheetService.GetSheet(schema.name);
            return Ok(data);
        }

        public class Schema
        {
            public string name { get; set; }
        }
相关问题