Reputation: 5709
I got the following address:
api/users/AddNew/<object here>
And so, I did something like this to test it out:
api/users/AddNew/{"Id":0,"NameFirst":"NewUser","NameLast":"NewUserLast","DateOfBirth":"2018/07/27"}
But all I get is a "This localhost page can't be found". Debugging in Visual Studio I set a breakpoint right when the code is supposed to trigger, but it never hits the debug point. Code below:
[HttpPost(Name = "AddNew")]
[Route("AddNew/{jsonUser}")]
public ActionResult<User> Post([FromBody] User newUser)
{
if (newUser != null) // Debug Point here never triggers
{
return Facade.AddNewUser(newUser);
}
else
{
return new User() { Id = 0, NameFirst = ErrorCodeUtility.GetEnumName(ErrorCodes.API_INVALID_POST_OBJECT) };
}
}
The User Model:
public class User
{
public uint Id;
public String NameFirst;
public String NameLast;
public DateTime DateOfBirth;
}
So, I'm assuming I'm doing something wrong either with my request or my C# code, but I can't quite find out which one of them it is. Sorry I'm a bit new at this :)
Upvotes: 1
Views: 1229
Reputation: 32068
There are at least three problems here:
You cannot call a POST method by navigating to an URL, since that executes a GET. You need a tool such as Postman for this testing.
[FromBody]
means that the data will come as part of the body of the request, so the data would be ignored even if the request could be processed (which cannot be, as explained in point 1). Note, however, that since you are using ASP.NET Core 2.1, you don't actually need to use [FromBody]
as that is the default, as explained here.
You say you want to create a REST API. /AddNew
doesn't follow REST.
Your method should be:
[HttpPost]
public ActionResult<User> Post([FromBody] User newUser)
And your URL would then be:
localhost:somePort/api/users
Upvotes: 5