Azure / azure-functions-dotnet-worker-preview

MIT License
65 stars 19 forks source link

HttpRequestData Body property throws an error if missing #41

Closed BroMarduk closed 3 years ago

BroMarduk commented 3 years ago

Seems like it would be better if HttpRequestData.Body was set to Null instead of throwing NullReferenceException when it's not in a request...

Example:

using System.Collections.Generic;
using System.Net;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Pipeline;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;

namespace FunctionApp
{
    public static class Function4
    {

        [FunctionName("Function4")]
        public static HttpResponseData Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestData req,
            FunctionExecutionContext executionContext)
        {
            var logger = executionContext.Logger;

            // This throws a NullReferenceException so a try/catch is needed to check for a missing Body
            if (req.Body == null)
            {
            }

            logger.LogInformation("message logged");
            var response = new HttpResponseData(HttpStatusCode.OK);
            var headers = new Dictionary<string, string>();
            headers.Add("Date", "Mon, 18 Jul 2016 16:06:00 GMT");
            headers.Add("Content", "Content - Type: text / html; charset = utf - 8");

            response.Headers = headers;
            response.Body = "Welcome to .NET 5!!";

            return response;
        }
    }

}
alexanderbikk commented 3 years ago

Hi @BroMarduk please check this one The HttpRequestData was changed in the latest preview4 version. So probably this issue is no longer exists. Please check the Function5 example to see how to work with HttpRequestData

BroMarduk commented 3 years ago

Yes, this works as expected now with preview 4

string body = req.Body.HasValue ? Encoding.UTF8.GetString(req.Body.Value.Span) : string.Empty;