Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SetHttpResponseStatusCode without using reflection #2

Open
YaroslavKormushyn opened this issue Nov 28, 2023 · 0 comments
Open

SetHttpResponseStatusCode without using reflection #2

YaroslavKormushyn opened this issue Nov 28, 2023 · 0 comments

Comments

@YaroslavKormushyn
Copy link

Thanks for the example project!

To anyone wondering, if there's a better way of setting the response code on the HTTP response if a 401 or 403 happens:

Microsoft published a sample middleware doing just that https://github.com/Azure/azure-functions-dotnet-worker/blob/a5fc0632d233b242debfd1485e527315567b9b3a/samples/CustomMiddleware/ExceptionHandlingMiddleware.cs#L47-L58
You just need to update to the latest function worker package.
My version is:

  • Microsoft.Azure.Functions.Worker 1.20.0

So instead of doing reflection in the SetHttpResponseStatusCode method, you could do this:

public static async Task SetHttpResponseStatusCode(
    this FunctionContext context,
    HttpStatusCode statusCode)
{
    var httpResponse = (await context.GetHttpRequestDataAsync()).CreateResponse(statusCode);
    var httpOutputBindingFromMultipleOutputBindings = context.GetOutputBindings<HttpResponseData>()
        .FirstOrDefault(b => b.BindingType == "http" && b.Name != "$return");

    if (httpOutputBindingFromMultipleOutputBindings is not null)
    {
        httpOutputBindingFromMultipleOutputBindings.Value = httpResponse;
    }
    else
    {
        var invocationResult = context.GetInvocationResult();
        invocationResult.Value = httpResponse;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant