I have this simple Net Core Web API HttpPut method to update an object called BakeCookieRecipe
.
It works fine if the user passes in an id
and BakeCookieRecipe
object,
but if someone usint the API forgets to pass in the id
and/or an empty BakeCookieRecipe
object, the browser throws a 404 error.
I guess that's fine, but I also want to log the event with my logger.
But for some reason, I can't catch when the id
and/or BakeCookieRecipe
is either missing or empty.
Here is my code. You can see where I am trying to test the id
and bakeCookieRecipe
object that is passed in and log it.
But it never does. It also never sends the NotFound
message I define.
Is there anything I can change to help me?
Thanks!
HttpPut("{id}")]
public async Task<IActionResult> PutBakeCookieRecipe(string id, BakeCookieRecipe bakeCookieRecipe)
{
if (string.IsNullOrWhiteSpace(id) || id != bakeCookieRecipe.BakeId)
{
Message = "id is missing or not found";
_logger.LogError(Message);
return NotFound("Id missing.");
}
if (!IsGuid(bakeCookieRecipe.CookieRecipeId.ToString()) || bakeCookieRecipe.CookieRecipeId == Guid.Empty)
{
Message = "RecipeId is missing";
_logger.LogWarning(Message);
return NotFound("RecipeId is missing or not found.");
}
_context.Entry(bakeCookieRecipe).State = EntityState.Modified;
await _context.SaveChangesAsync();
return NoContent();
}
// test to make sure a value is a Guid
private bool IsGuid(string value)
{
Guid x;
return Guid.TryParse(value, out x);
}
CodePudding user response:
I can't catch when the id and/or BakeCookieRecipe is either missing or empty.
By default, you would get 400 error directly without getting into the method In webapi projects
You could try remove the ApiController
and Route
attribute and remove the parameter in the constructor of HttpPut
attribute
[HttpPut]
public async Task<IActionResult> PutBakeCookieRecipe(string id, BakeCookieRecipe bakeCookieRecipe)
{
........
return NoContent();
}
Resgit the route in middleware as below:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(name: "RouteName", pattern: "Api/{controller}/{action}/{id?}");
});
Result:
CodePudding user response:
The problem causes using a new "smart" feature of Net6 that demands that all properties should be marked as nullable. And probably you are using API controller attribute. In this case an error is generated before in gets inside of the action. This is why you can't catch it. So if you have problem only here you can change the action
HttpPut("{id?}")]
public async Task<IActionResult> PutBakeCookieRecipe(string id, BakeCookieRecipe? bakeCookieRecipe)
search this site, especially my answers, how to to get rid of this error forever.
If you wanna cath the parameters values, just remove an [ApiController] attribute for testing