Prasad
Prasad

Reputation: 31

Web Api core 2.0 Controller method input parameter validation

How do you validate a JObject input parameter to a controller method? I am wondering is there any framework supported functions to validate easily?

Right now I am validating against null, if it is not null the JObject is parsed and populated the DTO object and complete the business process.

My controller method looks like below:

public async Task<IActionResult> Login([FromBody]JObject jObject)
{
    try
    {
        if (jObject != null)
        {                    
            TokenDTO SiBagToken = await _account.Login(jObject);

            return SuccessStatusCode;

        }
        else
        {
            return NoContentStatusCode;
        }

    }
    catch(Exception ex)
    {

        return errorstatuscode;

    }          

}   

Here is the DTO object looks like:

public class AccountDTO
{
    public string UserName { get; set; }
    public string Password { get; set; }
    public string oldPassword { get; set; }
}

Upvotes: 2

Views: 1242

Answers (1)

Nkosi
Nkosi

Reputation: 247018

Let the framework parse the desired object model by making it a parameter of the action.

Validation attributes can be applied to the DTO

For example

public class AccountDTO {
    [Required]
    [StringLength(50, ErrorMessage = "Your {0} must be contain between {2} and {1} characters.", MinimumLength = 5)]
    public string UserName { get; set; }
    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    public string oldPassword { get; set; }
}

And verified in the action using the controller's ModelState.

public async Task<IActionResult> Login([FromBody]AccountDTO model) {
    try {
        if (ModelState.IsValid) {  
            TokenDTO SiBagToken = await _account.Login(model);
            return Ok();
        }
        return BadRequest(ModelState);            
    } catch(Exception ex) {
        return errorstatuscode;
    }          
}

Upvotes: 2

Related Questions