Azure / azure-functions-dotnet-worker

Azure Functions out-of-process .NET language worker
MIT License
418 stars 181 forks source link

How to validate the Body of a POST Request? #1504

Open danielniccoli opened 1 year ago

danielniccoli commented 1 year ago

Before I ask my questions, let me quickly tell you that I have experience in Django and just started ASP.NET Blazor Pages with EF Core. I understand and appreciate the concept of model validation in ORM frameworks. In Both these frameworks are Models that are essentially a class that does attribute validation. Here is an example of that using ASP.NET:

public class Movie
{
    public int Id { get; set; }

    [Required]
    [StringLength(100)]
    public string Title { get; set; } = null!;

    [ClassicMovie(1960)]
    [DataType(DataType.Date)]
    [Display(Name = "Release Date")]
    public DateTime ReleaseDate { get; set; }

    [Required]
    [StringLength(1000)]
    public string Description { get; set; } = null!;

    [Range(0, 999.99)]
    public decimal Price { get; set; }

    public Genre Genre { get; set; }

    public bool Preorder { get; set; }
}

Now you can take the body of a POST request, deserialise it to a Movie object and then check if the JSON body would deserialise to a valid Movie object:

public async Task<IActionResult> Create(Movie movie)
{
    if (!ModelState.IsValid)
    {
        return View(movie);
    }

    _context.Movies.Add(movie);
    await _context.SaveChangesAsync();

    return RedirectToAction(nameof(Index));
}

I plan to use Azure Functions to create an API that's essentially a middle ware to creating users in AzureAD. I'm wondering how to approach validation in this scenario. Ideally, this is handled not in the function directly, but in a model class. I plan to have a base class AzureADUser with several other classes Employee, Freelancer, etc. that inherit from AzureADUser.

I found several old articles that describe how this could be approached, but I lack experience with both, ASP.NET and C# to really understand this approach, and also translate it from in-process to isolated.

There is also one more with Fluent Validation. Besides also being in-process, I prefer to use "built-in" functionality.

I'm wondering how to approach validation. I haven't found anything related to this in the Azure Functions docs, but I'm pretty sure that - especially with HTTP triggers - there are already established processes for that using the Azure Functions isolated mode. It would be great, if someone who does this already, could explain their approach. Or help me translate this so it works with the isolated mode. This then could also be a great addition to the Azure Function documentation.

danielniccoli commented 1 year ago

My research yielded the following: