简体   繁体   中英

How to Validate parameter in asp.net core 3.0 web api's get request?

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.

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.

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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM