3

I'm working on a minimal API in .NET Core 6 with OpenApi support.

I have a Resolution model defined like this:

using System.ComponentModel.DataAnnotations;

public struct Resolution
{
    [Required, Range(1, 800)]
    public int W { get; set; }

    [Required, Range(1, 600)]
    public int H { get; set; }
}

Then I have a POST endpoint definition like this:

app.MapPut("/resolutions", (Resolution res) =>
{
    //Some logic here
    return Results.Ok(new { Message = "Resource updated successfully" });
})
.Produces(200)
.Produces(404)
.WithName("PutResolution");

Case 1. I send a PUT request (out of range value fore w):

"resolution": {
    "w": 1024,
    "h": 400
}

Result: 200 OK.

Case 2: I send a PUT request (wrong data type for w):

"resolution": {
    "w": "xl",
    "h": 400
}

Result: 400 JsonException

Issue:

  • relying on JsonException on deserialization. Preferably a schema validation error should be returned to consumer.

Questions:

  1. What is the best practice to handle validation in this case?
  2. Is there a way to validate incoming request against the OpenApi contract, which in this case, is generated on the fly? In this case both wrong data type and value out of range issues would be validated before entering the route handler.

2 Answers 2

1

As mentioned in this document,There's no built-in support for validation in .NET 6 Minimal API.

If you do want it, you could try third party solutions such as this blog.

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

Comments

0

Solved using NuGet package: MiniValidation (https://www.nuget.org/packages/MiniValidation/) as suggested by @Ruikai. It would still fail on deserialization I can compromise on this.

Usage:

static async Task<IResult> PutImage(string id, Image image)
{
  if(!MiniValidator.TryValidate(image, out var errors))
  {
    return Results.ValidationProblem(errors);
  }
}

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.