How to validate request for Azure Functions

Tsuyoshi Ushio
2 min readSep 1, 2018

--

You might want to validate the HttpRequest using Azure Functions. However, we don’t have any implementation on the Azure Functions now. I see the issue , however it is not yet.

This is just a small idea to achieve validation on Azure Functions. I discussed with my Master Sensei, Kazuki Ota. I’ll share with the outcome.

Validation target

I want to validate a model object. C# have a great functionality of Validation in System.ComponentModel.DataAnnotations. You can validate using this library.

public class Movie
{
public string Id { get; set; }
[Required]
[StringLength(5)]
public string Title { get; set; }
[Range(0, 999.99)]
public decimal Price { get; set; }
}

Strategy

We need to call Validator.TryValidateObject(movie,...) However, I don’t write it on my Functions everytime. Ideally, I want Validate(model) method on my Functions. Since Functions is static class, it might be difficult. I eventually, write an extension method on HttpRequest. It might be second best. However, if you know better way, please let me know.

HttpResponseBody

This class represent a body of HttpResponse<T>. This method deserialize the target object with model validation. IsValid method will return if the model is valid or not. Also it contains, deserialized object and Validation Results.

HttpRequestExtensions

This class extend GetBodyAsync<T>() method which returns HttpResponseBody . Inside the method, it validate the object.

Usage

Then, Azure Functions looks like this.

Conclusion

Since Azure Functions bindings have converter, If we send pull request for HttpTrigger, then we might directory return the HttpRequestBody object. However, I don’t know whether people loves this idea or not.

[FunctionName("Function1")]
public static async Task<IActionResult> Run([HttpTrigger(...) HttpRequestBody body, ILogger log) {
:

I share this blog for thinking about the best way to handle validation for Azure Functions. If you have better idea please let me know.

This is the whole sample code.

--

--