skip to Main Content

Is it possible to automatically bind a model in a parameter in Azure Functions? Similar to how it is done in WebApi controllers? Essentially, when a post body is received, it would be automatically deserialized. And when a query is received, it would also be automatically deserialized. Alternatively, do you have a reliable manual implementation for doing this? Thanks.

2

Answers


  1. POST in Azure Functions:

    public async Task Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log)
    {          
       var messageJson = await new StreamReader(req.Body).ReadToEndAsync();
       var myModel = JsonConvert.DeserializeObject<ModelDto>(messageJson);
       
       //do something   
    }
    

    GET in Azure Functions:

    public async Task Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, ILogger log)
    {
       // BODY          
       var messageJson = await new StreamReader(req.Body).ReadToEndAsync();
       var myModel = JsonConvert.DeserializeObject<ModelDto>(messageJson);
       
       // QUERY - assuming you are sending json as a query parameter
       string queryJson = req.Query["myQuery"];
       var myModel2 = JsonConvert.DeserializeObject<ModelDto>(queryJson);
       //do something   
    }
    

    NOTE: If you need to send body in a GET request there is something wrong with the logic. In HTTP, GET method is specifically defined to not to include a request body.

    Login or Signup to reply.
  2. I hope it helps. Alternatively, add header deserialization.

    Query – Get

    public T AsQueryResult<T>(FunctionContext executionContext)
    {
        var queryParameters = executionContext.BindingContext.BindingData.SingleOrDefault(x => x.Key == "Query");
    
        var queryJson = queryParameters.Value!.ToString();
    
        return JsonConvert.DeserializeObject<T>(queryJson); 
    }
    

    Body – Post

    public T AsBodyResult<T>(HttpRequest req)
    {
        var body = new StreamReader(req.Body).ReadToEnd();
    
        return JsonConvert.DeserializeObject<T>(body);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search