0

I am trying to get the Header values from a Azure Function HTTP Trigger.

I have a Blazor Wasm Client.

When I use the Client, the Headers collection is empty.

I have the same version of the code working with a my Blazor Wasm Client calling a REST API. When I set up that version, I had to set up a CORS policy like the code below in my Startup.cs.

Once I added this code, my Blazor Wasm Client got the Header values from my API.

            services.AddCors(options =>
            {
                options.AddPolicy(StringConstant.AllowedSpecificOrigins,
                    builder =>
                    {
                        builder.WithOrigins(origins)
                            .AllowAnyHeader()
                            .AllowAnyMethod()
                            .WithExposedHeaders("*");
                    });
            });

It looks like I have to do the same from my Azure Function since the Header collection is empty in my Response object.

Any idea on how to set this up?

My Blazor Wasm Client is using the httpClient.GetAsync method.

Richard
  • 1,054
  • 1
  • 19
  • 36
  • Have you tried [setting it in the Azure portal](https://www.c-sharpcorner.com/article/handling-cors-in-azure-function/)? – stuartd Aug 08 '21 at 22:11
  • Thanks for the reply. No I am working locally. Can you do this in the portal? – Richard Aug 08 '21 at 22:22
  • From the link above, yes you can set up CORS in the portal - https://imgur.com/a/5ic2RRq - though I’m not sure about `WithExposedHeaders` .Locally though - which I haven’t had to do for a while - possibly not.. – stuartd Aug 09 '21 at 00:02
  • Hi Richard. I'm in exactly the same situation as you. Did you manage to resolve? – Walter Lockhart Dec 04 '21 at 17:53
  • @WalterLockhart No I never got this resolved. In was a PIC app so it was not critical. So, I really didn't spend much more time on this issue. If you come up with a solution, please let me know. TY – Richard Dec 22 '21 at 21:26
  • @WalterLockhart see https://stackoverflow.com/a/71080645/9276081 – Bandook Feb 11 '22 at 13:18

2 Answers2

2

We can add CORS in our Function App from Azure Portal.

Below is the place where we can add from Azure Portal:

enter image description here

Add * if we want to allow all origins or else, we can add the URLs include them specifically.

Refer to few related documentation from Microsoft about CORS in Portal, With Code

SaiKarri-MT
  • 1,174
  • 1
  • 3
  • 8
0

Found the solution - https://stackoverflow.com/a/71080532/9276081, I've pasted my answer here as well -

The issue is not with Blazor WASM, rather if that header has been exposed on your API Side. In your azure function, add the following -

Note: Postman will still show the headers even if you don't expose the headers like below. That's because, Postman doesn't care about CORS headers. CORS is just a browser concept and not a strong security mechanism. It allows you to restrict which other web apps may use your backend resources and that's all.

First create a Startup File to inject the HttpContextAccessor

Package Required: Microsoft.Azure.Functions.Extensions

[assembly: FunctionsStartup(typeof(FuncAppName.Startup))]

namespace FuncAppName
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddScoped<HttpContextAccessor>();
        }
    }
}

Next, inject it into your main Function -

using Microsoft.AspNetCore.Http;
namespace FuncAppName
{
    public class SomeFunction
    {
        private readonly HttpContext _httpContext;
        public SomeFunction(HttpContextAccessor contextAccessor)
        {
             _httpContext = contextAccessor.HttpContext;
        }

        [FunctionName("SomeFunc")]
        public override Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, new[] { "post" }, Route = "run")] HttpRequest req)
        {
            var response = "Some Response"
            _httpContext.Response.Headers.Add("my-custom-header", "some-custom-value");
            _httpContext.Response.Headers.Add("my-other-header", "some-other-value");
            _httpContext.Response.Headers.Add("Access-Control-Expose-Headers", "my-custom-header, my-other-header");
            return new OkObjectResult(response)
        }

If you want to allow all headers you can use wildcard (I think, not tested) -

_httpContext.Response.Headers.Add("Access-Control-Expose-Headers", "*");

You still need to add your web-app url to the azure platform CORS. You can add * wildcard, more info here - https://iotespresso.com/allowing-all-cross-origin-requests-azure-functions/

to enable CORS for Local Apps during development - https://stackoverflow.com/a/60109518/9276081

Now to access those headers in your Blazor WASM, as an e.g. you can -

protected override async Task OnInitializedAsync()
{
    var content = JsonContent.Create(new { query = "" });
    using (var client = new HttpClient())
    {
        var result = await client.PostAsync("https://func-app-name.azurewebsites.net/api/run", content);
        var headers = result.Headers.ToList();
    }
}
Bandook
  • 658
  • 6
  • 21
  • 1
    The accepted answer in https://stackoverflow.com/a/71080532/9276081 mentions the host.json file. Which is easier to setup. – craziac Jan 11 '23 at 14:08