Home > other >  Azure function .net 6 return error 500 after deploy
Azure function .net 6 return error 500 after deploy

Time:04-14

I've migrated a project from .net core 3.1 to .net 6.0. I've resolved/updated all nugets and my functions runs well on local environments (I've tested on two pcs). The project has an http trigger and connection to database. When I call the api using postman and it's not necesary in logic connect to database my function return 200 on http status code and expected response body. However, when the function needs connect to database I see on log that the functions get results from database althoug all logic runs well when the function return the response return an error 500.

Any logs regarding to an exception is showed on azure functions logs, I search the data application logs files on kudu as well, but I ddidn't find anything related to the issue

Azure Logs (data in red was retrieved from database) Azure logs

Postman Postman

Project configuration

Nugets

Nugets

Project

enter image description here

Azure Function properties

  • FUNCTIONS_EXTENSION_VERSION: ~4

  • Runtime version: ~4

  • FUNCTIONS_WORKER_RUNTIME: dotnet

Azure Function code

 [FunctionName("FnDealSlip")]
    public async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", Route = "v1/fintech/dealslip")] HttpRequest req,
        ILogger log)
    {

        string offerDate = req.Query["offerDate"];

        try
        {
            return await Invoke(req, log, (request, logger) =>
            {
                return _dealSlipService.GetDealSlipByOfferDate(offerDate);

            },
      (response, httpRequest, logger) =>
      {
          log.LogInformation("Response: "   JsonFormartter.Serialize(response));
          log.LogInformation("Response Status Code: "   JsonFormartter.Serialize(response.StatusCode));
          var actionResponse = new ObjectResult(response)
          {
              StatusCode = response.StatusCode

          };
          log.LogInformation("Response actionResponseSet: true ");
          return actionResponse;
      });
        }
        catch (Exception ex)
        {
            log.LogError("error fn: "   ex.Message);
            throw;
        }
      
    }

CodePudding user response:

  • Because an HTTP Function is expected to return an HTTP result, consider changing it to:
public static async Task<HttpResponseMessage> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, 
    ILogger log)
{
    // your code goes here
    return req.CreateResponse(HttpStatusCode.OK, "Done");
  • The 500 internal errors occur even before our code is executed. When the client that uses the HTTP function returns a 500 error, there are no exceptions in the actual HTTP Trigger function.
  • It's also worth noting that when the 500 error occurs, No Single function works. As a result, All HTTP Functions begin returning the 500 status code at the same moment. And none of them appear to be logging anything.
  • You've checked that your code works locally, but when you publish it to an Azure function, you get a 500 error. In that instance, it appears that there is some configuration in your local.setting.json that was not created in the azure function under the application setting.
  • I'd also recommend looking over Azure Functions diagnostics to figure out what's causing the 500 problem.

CodePudding user response:

I built code below for testing pusposes. I see that everytime a task is invoked and this taked more than 2s, I'm getting error 500 with any log, so, I assume this behavior provoke the error I'm facing. Any idea what have changed from .net core 3.1 regadirng this type of request?

 [FunctionName("Function1")]
    public async Task<IActionResult> Run(
       [HttpTrigger(AuthorizationLevel.Function, "get", Route = "v1/fintech/dealslip")] HttpRequest req,
       ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");
        string offerDate = req.Query["offerDate"];


        switch (offerDate)
        {
            case "2021-12-27": 
                await Task.Delay(1000);//Just this works
                break;
            case "2021-12-28":
                await Task.Delay(2000);
                break;
            case "2021-12-29":
                await Task.Delay(3000);
                break;
            default:

                break;
        }
        string responseMessage = string.IsNullOrEmpty(offerDate)
           ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
           : $"Hello, {offerDate}. This HTTP triggered function executed successfully.";

        return new OkObjectResult(responseMessage);

     
    }

This is my startupfile

[assembly: FunctionsStartup(typeof(StartUp))]

namespace FunctionApp1 {

public class StartUp : FunctionsStartup
{

    public override void Configure(IFunctionsHostBuilder builder)
    {

        builder.Services.AddTransient<IRetry, RetryHelper>();
        builder.Services.AddTransient<ISecurity, SecurityService>();
        builder.Services.AddTransient<IAuthServiceToken, AzureServiceToken>();
        builder.Services.AddTransient<INotificationSender, NotificationSender>();
        builder.Services.AddTransient<IDealSlipService, DealSlipService>();
        builder.Services.AddDbContext<DataContext, DataContext>();
        builder.Services.AddTransient(typeof(IRepository<>), typeof(Repository<>));

        builder.Services.AddSingleton(typeof(IAppSettings), x =>
        {
            var configBuilder = new ConfigurationBuilder().AddEnvironmentVariables();

            string vault = Environment.GetEnvironmentVariable(Constants.Settings.KeyVaultUri);
            var secretClient = new SecretClient(new Uri(vault),
                                                     new DefaultAzureCredential());
            configBuilder.AddAzureKeyVault(secretClient, new KeyVaultSecretManager());

            var config = configBuilder.Build();
            return AppSettingBuilder.Build<FintechSettings>(config);
        });

    }





}

}

  • Related