最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - Azure Function App with Authorization Middleware throwing 500 exception - Stack Overflow

programmeradmin5浏览0评论

I have an Azure Functions App v4, running as dotnet-isolated. I am trying to simplify my JWT authorization code by using a custom attribute and custom middleware that will check the token. However, I'm hitting some problems with the function throwing a 500 error if my middleware tries to return an http Response to the FunctionContext. I've simplified the example, removing the attribute and simply having the middleware that always returns a 401:

    internal class AuthorizationMiddleware : IFunctionsWorkerMiddleware
    {
        public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
        {
            try
            {
                var httpRequestData = await context.GetHttpRequestDataAsync();
                if ((httpRequestData == null))
                {
                    Console.WriteLine("Request is NULL, calling next()");
                    await next(context);
                    return;
                }

                var httpResponse = httpRequestData!.CreateResponse(HttpStatusCode.Unauthorized);
                await httpResponse.WriteStringAsync("unauthorized");
                context.GetInvocationResult().Value = httpResponse;
                return;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"Error in AuthorizationMiddleware: {ex.Message}");
                throw;
            }
        }
    }

This is the program.cs

    private static void Main(string[] args)
    {
        var builder = FunctionsApplication.CreateBuilder(args);

        builder.UseMiddleware<ExceptionHandlingMiddleware>();
        builder.UseMiddleware<AuthorizationMiddleware>();

        builder.ConfigureFunctionsWebApplication();

        builder.Build().Run();
    }

My environment: Windows 10, Visual Studio 2022, .Net 8, Azure Functions v4, using these packages:


    <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="2.0.0" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.2.0" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="2.0.0" />
    <PackageReference Include="Microsoft.Azure.WebJobs" Version="3.0.41" />

From all the code examples I've seen, I should be seeing a 401 being returned, instead it runs through all my code successfully in the debugger, and then a couple of seconds later I get a 500 Internal Server Error.

The error wasn't giving me proper details, so I added middleware to trap all exceptions and the exception I get is null, but I look at the contents of it, I get these values:

System.Exception.InnerExceptionPrefix: "--->"

System.Exception._COMPlusExceptionCode : -532462766

Any suggestions? It's looking to me like it might be a bug in .Net?

I have an Azure Functions App v4, running as dotnet-isolated. I am trying to simplify my JWT authorization code by using a custom attribute and custom middleware that will check the token. However, I'm hitting some problems with the function throwing a 500 error if my middleware tries to return an http Response to the FunctionContext. I've simplified the example, removing the attribute and simply having the middleware that always returns a 401:

    internal class AuthorizationMiddleware : IFunctionsWorkerMiddleware
    {
        public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
        {
            try
            {
                var httpRequestData = await context.GetHttpRequestDataAsync();
                if ((httpRequestData == null))
                {
                    Console.WriteLine("Request is NULL, calling next()");
                    await next(context);
                    return;
                }

                var httpResponse = httpRequestData!.CreateResponse(HttpStatusCode.Unauthorized);
                await httpResponse.WriteStringAsync("unauthorized");
                context.GetInvocationResult().Value = httpResponse;
                return;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"Error in AuthorizationMiddleware: {ex.Message}");
                throw;
            }
        }
    }

This is the program.cs

    private static void Main(string[] args)
    {
        var builder = FunctionsApplication.CreateBuilder(args);

        builder.UseMiddleware<ExceptionHandlingMiddleware>();
        builder.UseMiddleware<AuthorizationMiddleware>();

        builder.ConfigureFunctionsWebApplication();

        builder.Build().Run();
    }

My environment: Windows 10, Visual Studio 2022, .Net 8, Azure Functions v4, using these packages:


    <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="2.0.0" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.2.0" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="2.0.0" />
    <PackageReference Include="Microsoft.Azure.WebJobs" Version="3.0.41" />

From all the code examples I've seen, I should be seeing a 401 being returned, instead it runs through all my code successfully in the debugger, and then a couple of seconds later I get a 500 Internal Server Error.

The error wasn't giving me proper details, so I added middleware to trap all exceptions and the exception I get is null, but I look at the contents of it, I get these values:

System.Exception.InnerExceptionPrefix: "--->"

System.Exception._COMPlusExceptionCode : -532462766

Any suggestions? It's looking to me like it might be a bug in .Net?

Share Improve this question asked Mar 27 at 12:30 John McArthurJohn McArthur 1,0361 gold badge17 silver badges34 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

I have tested your simplified code and able get Unauthorized as response.

Sharing the code which worked for me.

Program.cs:

using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Builder;
using Microsoft.Azure.Functions.Worker.Middleware;
using Microsoft.Extensions.Hosting;

var builder = FunctionsApplication.CreateBuilder(args);

builder.ConfigureFunctionsWebApplication();
builder.UseMiddleware<ExceptionHandlingMiddleware>();
builder.UseMiddleware<AuthorizationMiddleware>();

builder.Build().Run();

AuthorizationMiddleware:cs

using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Azure.Functions.Worker.Middleware;

namespace FunctionApp19
{
    public class AuthorizationMiddleware : IFunctionsWorkerMiddleware
    {
        public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
        {
            try
            {
                var httpRequestData = await context.GetHttpRequestDataAsync();
                if ((httpRequestData == null))
                {
                    Console.WriteLine("Request is NULL, calling next()");
                    await next(context);
                    return;
                }

                var httpResponse = httpRequestData!.CreateResponse(HttpStatusCode.Unauthorized);
                await httpResponse.WriteStringAsync("unauthorized");
                context.GetInvocationResult().Value = httpResponse;
                return;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"Error in AuthorizationMiddleware: {ex.Message}");
                throw;
            }
        }
    }
}

ExceptionHandlingMiddleware.cs:

using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Middleware;
using Microsoft.Azure.Functions.Worker.Http;
using System;
using System.Net;
using System.Threading.Tasks;

public class ExceptionHandlingMiddleware : IFunctionsWorkerMiddleware
{
    public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
    {
        try
        {
            await next(context);
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"Error in function execution: {ex.Message}");
            var httpRequestData = await context.GetHttpRequestDataAsync();
            if (httpRequestData != null)
            {
                var httpResponse = httpRequestData.CreateResponse(HttpStatusCode.InternalServerError);
                await httpResponse.WriteStringAsync("An error occurred while processing your request.");
                context.GetInvocationResult().Value = httpResponse;
            }
            else
            {
                throw new InvalidOperationException("This middleware currently only handles HTTP requests.");
            }
        }
    }

Function.cs:

  • Created a Http triggered Azure function.
public class Function1
{
    private readonly ILogger<Function1> _logger;

    public Function1(ILogger<Function1> logger)
    {
        _logger = logger;
    }

    [Function("Function1")]
    public IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequest req)
    {
        _logger.LogInformation("C# HTTP trigger function processed a request.");
        return new OkObjectResult("Welcome to Azure Functions!");
    }
}

.csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <AzureFunctionsVersion>v4</AzureFunctionsVersion>
    <OutputType>Exe</OutputType>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="2.0.0" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="2.0.0" />
  </ItemGroup>
  <ItemGroup>
    <None Update="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </None>
  </ItemGroup>
  <ItemGroup>
    <Using Include="System.Threading.ExecutionContext" Alias="ExecutionContext"/>
  </ItemGroup>
</Project>

Output:

Functions:

        Function1: [GET,POST] http://localhost:7153/api/Function1

For detailed output, run func with --verbose flag.
[2025-03-27T16:57:00.925Z] Host lock lease acquired by instance ID '000000000000000000000000F72731CC'.
[2025-03-27T16:57:37.927Z] Executing 'Functions.Function1' (Reason='This function was programmatically called via the host APIs.', Id=f033bfe6-4326-4450-ba12-48afd715e3b4)
[2025-03-27T16:58:07.447Z] Executed 'Functions.Function1' (Succeeded, Id=f033bfe6-4326-4450-ba12-48afd715e3b4, Duration=29593ms)

发布评论

评论列表(0)

  1. 暂无评论