Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - Validate query parameters without using a model in .netcore api

Is it possible to validate query parameters on an action without using a model? A lot of the calls in my API are one-offs and I don't see a point in making models for them if they will only be used one time.

I saw the following article, which seemed like it was exactly what I needed, except I don't want it to return a 404 if the required parm doesn't exist, I want it to return an object of error messages similar to the baked in model validation - really, I just want the parameters to be treated like a model, without actually having to make a model.

https://www.strathweb.com/2016/09/required-query-string-parameters-in-asp-net-core-mvc/

[HttpPost]
public async Task<IActionResult> Post(
    [FromQueryRequired] int? Id,
    [FromQuery] string Company)

EDIT:
The [FromQueryRequired] is a custom ActionConstraint that throws a 404 if the ID parm is missing (this was taken directly from the article). However I don't want the 404, I want an object that has a message that says {MESSAGE: "ID is required"}. I think the issue is that i can't access the Response context from within an Action Constraint.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

From Asp.Net Core 2.1 there is a built-in parameter [BindRequired] which is doing this validation automatically.

public async Task<ActionResult<string>> CleanStatusesAsync([BindRequired, 
    FromQuery]string collection, [BindRequired, FromQuery]string repository,
       [BindRequired, FromQuery]int pullRequestId)
{
    // all parameters are bound and valid
}

If you are calling this method without parameters, a ModelState error is returned:

{
"collection": [
  "A value for the 'collection' parameter or property was not provided."
],
"repository": [
  "A value for the 'repository' parameter or property was not provided."
],
"pullRequestId": [
  "A value for the 'pullRequestId' parameter or property was not provided."
],
}

More details you can find in this excellent article.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...