I have the following function that should return either a 200 response with a book as payload or a 404 with empty body:
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.Functions.Worker;
public class Function1
{
private readonly ILogger<Function1> _logger;
public Function1(ILogger<Function1> logger)
{
_logger = logger;
}
private static readonly Dictionary<string, string> items = new Dictionary<string, string>
{
{ "1", "Book 1" },
{ "2", "Book 2" },
{ "3", "Book 3" }
};
[Function("GetItem2")]
public async Task<IActionResult> GetItemAsync([HttpTrigger(AuthorizationLevel.Function, "get", Route = "GetItem2/{id}")] HttpRequest request,
string id,
CancellationToken c)
{
_logger.LogInformation($"Received request for item with id: {id}");
await Task.Delay(100, c);
if (items.TryGetValue(id, out var item))
{
return new OkObjectResult(item);
}
else
{
return new NotFoundResult();
}
}
}
It works as expected in .NET 6 and running on Azure functions with the in-process model.
I am upgrading it to .NET 8 and an isolated worker model, and now response changed! it always returns 200, with the request details in the payload:
I wonder what caused this change in behaviour and how do I fix it? Of course I do not want to wrap http statuses in the response payload.
I am using the following Program.cs:
var host = new HostBuilder()
.ConfigureAppConfiguration((context, config) =>
{
config.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true);
config.AddEnvironmentVariables();
})
.ConfigureFunctionsWorkerDefaults()
.ConfigureServices(ConfigureServices)
.ConfigureLogging((context, logging) =>
{
logging.AddConfiguration(context.Configuration.GetSection("Host:Logging"));
})
.Build();
host.Run();
static void ConfigureServices(HostBuilderContext builderContext, IServiceCollection serviceCollection)
{
}
2
Answers
Turns out replacing
ConfigureFunctionsWorkerDefaults()
withConfigureFunctionsWebApplication()
fixes my problem. I do not know what these function does and why the first gives broken http responses. Would love if someone could explain a bit!I have modified your code as below and it worked:
Function.cs:
Update:
ConfigureFunctionsWebApplication()
inProgram.cs
, refer MSDOC.Program.cs:
Output when item not found:
Output when Item found: