0

I have struggle with binding POST data. Here's my example with one parameter (string name) which is always null. If I use [FromBody] attribute there's exception in debug log but no message.

Some client side code.

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

Controller action.

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

Request.

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

Debug log with [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

Debug log without [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
  • yes, it doesn't matter Commented Apr 21, 2020 at 8:55

1 Answer 1

0

I found solution. I create class and pass it as argument to action.

Example below. Still don't know why parsing single argument failed. I've tried to pass { "name": "someName"}, and without brackets - just "someName". It didn't worked. In ModelState object there was always error message:

unexpected character encountered while parsing value: {. Path '', line 1, position 1.

or when I pass just value (someName)

unexpected character encountered while parsing value: s. Path '', line 1, position 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; }
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.