Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

c# - Required query string parameter in ASP.NET Core

Using ASP.NET Core 1.1 with VS2015 (sdk 1.0.0-preview2-003131), I have the following controller:

public class QueryParameters
{
    public int A { get; set; }
    public int B { get; set; }
}

[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET api/values
    [HttpGet]
    public IEnumerable<string> Get([FromQuery]QueryParameters parameters)
    {
        return new [] { parameters.A.ToString(), parameters.B.ToString() };
    }        
}

As you can see, I have two query parameters. What I would like is to have one of them (ex: A) to be required. That is, I would like to use an attribute (if possible) to say that this attribute is required. Then, I would like like ASP.NET to do this validation before even calling my controller.

I would have liked to use the Newtonsoft RequiredAttribute to use the same attributes as I already use to validate the required properties in the PUT/POST content, but since the url is not a JSON string, it is obviously not used.

Any suggestion to have ASP.NET Core automatically check for required query parameters?

Note that I know that I can code the check myself using nullable query parameters but that beats the purpose of letting ASP.NET do the validation before calling my controller, thus keeping my controller tidy.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In ASP.NET Core 2.1 and above you can use top level parameters validation. You can put attributes on parameters

    [HttpGet]
    public IActionResult GetDices([BindRequired, Range(1, 6)]int number)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest("Invalid number");
        }

            return Ok(_diceRepo.GetDices(number));
    }

More about this https://programmingcsharp.com/asp-net-parameter-validation/#Top-level_node_validation


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...