3

I have problem in Fetch POST to controller, an showing error like {"errors":{"":["Unexpected character encountered while parsing number: W. Path '', line 1, position 6."]},"title":"One or more validation errors occurred.","status":400,"traceId":"0HLOGKVEBUTKL:00000007"}. When I debbug too, in my controller it's not passing to controller.

This what I POST to

enter image description here enter image description here

I'm using ReactJs for client-side, and Net Core for server-side. Here my code snippet:

AddList.js

 fetch('api/SampleData/AddEmployee', {
   method: 'POST',
   headers: {
     'Accept': 'application/json; charset=utf-8',
     'Content-Type': 'application/json;charset=UTF-8'
   },
   body: data,
 }).then((response) => response.json())
 .then((responseJson) => {
   console.log('Success:', JSON.stringify(responseJson));
   this.props.history.push("/list-data");
 })
   .catch(error => console.error('Error:', error));

SampleDataController.cs

[HttpPost("[action]")]
public JsonResult AddEmployee(EmployeesViewModel employee)
{
}

starrup.cs

 app.UseMvc(routes =>
 {
   routes.MapRoute(
     name: "default",
     template: "{controller}/{action=Index}/{id?}");

   routes.MapRoute(
     name: "api",
     template: "api/{controller}/{action}/{id?}");
 });
4
  • can you try it without Content-Type. It worked for me when i was dealing with formdata Commented Jul 25, 2019 at 3:49
  • different error {"type":"https://tools.ietf.org/html/rfc7231#section-6.5.13","title":"Unsupported Media Type","status":415,"traceId":"0HLOGKVEBUTKP:00000008"} Unsupported Media Type @mkamranhamid Commented Jul 25, 2019 at 3:55
  • I've no idea about .net but by seeing your error I guess your target resource should be explicitly told what kind of data it should be receiving in body like this 'Content-Type': 'multipart/form-data' Commented Jul 25, 2019 at 4:02
  • can you try this too Commented Jul 25, 2019 at 4:04

2 Answers 2

3

You dont need this config

   routes.MapRoute(
     name: "api",
     template: "api/{controller}/{action}/{id?}");

Instead use routing in your controller like this

[Route("api/[controller]/[action]")]
public class YourController : Controller
Sign up to request clarification or add additional context in comments.

Comments

0

Instead of

body: data,

can you try this?

body: JSON.stringify(data),

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.