Home > OS >  GUID is 00000000-0000-0000-0000-000000000000 when posting to .net core endpoint from axios, react an
GUID is 00000000-0000-0000-0000-000000000000 when posting to .net core endpoint from axios, react an

Time:01-06

I have a .net endpoint here:

public class ListContactRequest
{
    public Guid userId { get; set; }
}

[Authorize]
[HttPost]
[Route("listContacts")]
public async Task<AddressBookListContacts> listContacts([FromBody]ListContactRequest req)
{
     return blah blah....
}

and my react axios calls in typescript

import { Guid } from "guid-typescript";

interface IListContactRequest {
  userId: Guid;
}
const ListContacts = (user: IListContactRequest) => {
  console.log(user);
  return axios
    .post(API_URL   "/listContacts", user, {
      headers: {
        "Content-Type": "application/json",
      },
    })
    .then((response) => {
      return response.data;
    });
};

the problem is that, when the axios method fires, it reaches the .net endpoint,however, the guid within the parameter object, is coming through as 00000000-0000-0000-0000-000000000000

when console logging the front end, the guid is appearing correctly, but when it hits the backend api, it seems to not carry over.

can someone offer some advice?

console.log(JSON.stringify(user))  

shows

{"userId":{"value":"24883e12-439d-4e54-aae5-5b1d5140833e"}}

CodePudding user response:

Your Guid is serialising to JSON as an object with value property but your C# model does not match.

You can use either the Guid.prototype.toString() or Guid.prototype.toJSON() methods to get the correct value

axios.post("/listContacts", {
  userId: user.userId.toJSON().value // or user.userId.toString()
}, {
  baseURL: API_URL
});

See https://github.com/snico-dev/guid-typescript#props-and-methods


Perhaps a neater option would be to make IListContactRequest a class instead that implements its own toJSON() method

class ListContactRequest {
  constructor(readonly userId: Guid) {}

  toJSON() {
    return {
      userId: this.userId.toJSON().value,
    };
  }
}

const user = new ListContactRequest(Guid.create());
axios.post(url, user);

CodePudding user response:

The problem is that your endpoint is expecting an object like:

{
   "userId": "0d7b77dc-4d2a-4793-adb0-ec5a34698958"
}

And you are sending

{"userId":{"value":"24883e12-439d-4e54-aae5-5b1d5140833e"}}

So, it fails to deserialize it to the target type and just gives you the default value for Guid.

You either need to change the axios call to:

.post(API_URL   "/listContacts", user.UserId, {

Or if you must leave it like that you need to change your endpoint parameter to something like Dictionary<string, ListContactRequest>

  • Related