0

I want to validate the parameter in web api's get request. How to achieve this.

code:

[HttpGet("{id}")]

public async Task<ActionResult<Schedd>> GetSchedd(string id)  
{   
    return Ok(await _context.Schedds.FromSqlRaw<Schedd>("sp_userprofile {0},{1},{2}", id, 7, null).ToListAsync());  
}

Here String id must not contain any symbol or alphapet.

1
  • Do you want to allow only numbers in id parameter? Commented May 23, 2021 at 7:13

2 Answers 2

3

You can use a model validation attribute to validate a parameter:

Create a validation attribute to ensure your string only has numeric characters by inheriting from System.ComponentModel.DataAnnotations.ValidationAttribute and overriding ValidationResult to prohibit alphabet or symbol (i.e. non-numeric) characters (you can loop through each character and compare it against 0-9, but it's cleaner to use a regular expression here):

using System.ComponentModel.DataAnnotations.ValidationAttribute;

public class NumericStringAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (!ValidationRegex.IsMatch(value.ToString()))
        {
            return new ValidationResult("Numeric field must not have a non-numeric character.");
        }

        return ValidationResult.Success;
    }

    // Keep the expression compiled to improve performance.
    private static readonly Regex ValidationRegex = new Regex(@"^[0-9]*$", RegexOptions.Compiled);
}

Now you can apply this attribute to your parameter:

public async Task<ActionResult<Schedd>> GetSchedd([NumericString] string id)

This will cause the framework to set ModelState.IsValid to false if the validation fails, which you can now check inside the function body and return a bad request as required.

if (!ModelState.IsValid)
{
    return BadRequest();
}

This part is not necessary if you've applied the ApiControllerAttribute to your controller, because then validation errors are automatically handled by the framework with a BadRequest.

Sign up to request clarification or add additional context in comments.

Comments

1

You can solve this issue validating id parameter with a regular expression, if id doesn't match with pattern you should return a 400 http status (bad request):

[HttpGet("{id}")]
public async Task<ActionResult<Schedd>> GetScheddAsync(string id)
{
    // Define the regular expression
    var pattern = "...";
    
    // Validate id parameter with pattern using a regular expression
    var match = Regex.Match(id, pattern);

    if (!match.Success)
    {
        ModelState.AddModelError("Id", "The Id must not contains any symbol or alphabet");

        return BadRequest(ModelState);
    }

    return Ok(await _context.Schedds.FromSqlRaw<Schedd>("sp_userprofile {0},{1},{2}", id, 7, null).ToListAsync());
}

Also you need to import the following namespace: System.Text.RegularExpressions

Please let me know if this helps.

Comments

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.