Search code examples
asp.net-coreasp.net-web-apiangular7asp.net-core-routing

Parameters passed from angular 7 to my Asp.net core WebApi controller are all null


I have this code below and I want to pass two parameters from Angular 7 app to my Asp.Net Core WebApi controller, I just don't know the syntax for the Angular http post call to the controller. The controller is getting all null values when it's hit. But I can pass in a model it works just fine!

Question - here is what I don't understand. When I pass in a model like this

[HttpPost("confirm")]
public async Task<IActionResult> ConfirmEmail(EmailConfirmationOptions options) {}

and have my post pass in a model as well, like this. It works!

const model = {UserId: userId, Code: code };
return this.http.post(this.baseUrl + 'confirm', model);

Here is my Angular call where I've tried different values but none seem to pass them correctly.

confirm(userId: number, code: string) {
    // return this.http.post(this.baseUrl + 'confirm, { userId, code });
    // return this.http.post(this.baseUrl + 'confirm/' + userId + '/code/' + code, {});
    return this.http.post(this.baseUrl + 'confirm', userId);
}

Here is my controller, where userId comes in as 0 and code comes in a null

[AllowAnonymous]
//[HttpPost("confirm")]
//[HttpPost("{id}/{code}", Name = "confirm")]
// [HttpPost("{userId}", Name = "confirm")]
[HttpPost("confirm")]
public async Task<IActionResult> ConfirmEmail(string userId, string code) 
{
    if (userId == null || code == null)
    {
        return BadRequest("error");
    }

    var user = await _userManager.FindByIdAsync(userId);

    if (user == null) {
        return BadRequest("error");
    }

    // code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
    var result = await _userManager.ConfirmEmailAsync(user, code);

    if (result.Succeeded) {
        return Ok();
    } else {
        return BadRequest("error");
    } 
}

Solution

  • If the client side request looks like this

    return this.http.post(this.baseUrl + 'confirm/' + userId + '/code/' + code, {});
    

    The route template on the server would need to match the intended route

    [HttpPost("confirm/{userId}/code/{code}")]
    public async Task<IActionResult> ConfirmEmail(string userId, string code) {
        //...omitted for brevity
    }
    

    Reference Routing to controller actions in ASP.NET Core

    If the controller has the [ApiController] attribute, then try to be explicit about where the data is to be bound from

    [HttpPost("confirm/{userId}/code/{code}")]
    public async Task<IActionResult> ConfirmEmail([FromRoute]string userId, [FromRoute]string code) {
        //...omitted for brevity
    }
    

    Reference Model Binding in ASP.NET Core