2

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; }
}

1 Answer 1

2

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;
    }          
}
Sign up to request clarification or add additional context in comments.

4 Comments

Starting from version 2.1 there's no need for the manual IsValid check when annotated with [ApiController]: learn.microsoft.com/en-us/aspnet/core/web-api/…
@ChristophLütjen yes that is if you are using an [ApiController], but not by default. The information you provided is still accurate though.
Thank you for the response. So If I change the input parameter from JObject to DTO object, will the Angular UI understands?
@Prasad the DTO class is for the Server side. The JSON sent by the client will be parsed by the framework and passed to the controller action.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.