Home > Back-end >  API does not detect the headers
API does not detect the headers

Time:10-29

I'm working on my first Blazor app. I try to request a rest API to get data.

I already use this API with other applications, so I'm sure it works fine.

My HTTP request is rejected by my API: the API does not detect the headers I want to add, so the request is rejected.

In my API, I check my user and password:

 protected override bool CheckAccessCore(OperationContext operationContext)
    {
        string AuthHeader = WebOperationContext.Current.IncomingRequest.Headers["Authorization"];
        if(!string.IsNullOrWhiteSpace(AuthHeader))
        {
                return CheckCredentials(AuthHeader);
        }
        return false;
    }

This code works fine with others apps.

In my Blazor project, I call My API this way :

In Program.cs, I declare my Httpclient :

builder.Services.AddScoped(sp => new HttpClient{BaseAddress = new Uri("https://localhost:44346/MyServiceRest.svc")});
 builder.Services.AddScoped<ProjectModel.ClsMetierService>();

I add a constructor in my ClsMetierService class to get my scoped httpclient :

  HttpClient httpClient;
    public ClsMetierService(HttpClient _httpClient)
    {
        httpClient = _httpClient;

In my methode, I call my httpclient and set my headers :

 var requestMessage = new HttpRequestMessage()
        {
            Method = new HttpMethod("GET"),
            RequestUri = new Uri(urlStream)
        };

        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Authorization", System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("Admin:Password")));
requestMessage.Content.Headers.TryAddWithoutValidation("Test", "Value");

            var response = await httpClient.SendAsync(requestMessage);
            var responseStatusCode = response.StatusCode;

        JsonResult = await response.Content.ReadAsStringAsync();
        return JsonResult;

If I set a breakpoint in the CheckAccessCore in my API, the AuthHeader variable is null. I checked the incomingrequest.Headers, I get a list of 14 headers, none of them is "Authorization" or "test", as if my header were not added to my request: enter image description here

I thought the problem was because of the TryAddWithoutValidation method, but my second header "test" does not exist either.

I usually use a HttpWebRequest and to this way :

httpReq.Headers.Add("Authorization", System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("login:password")));

But with Blazor WebAssembly I get this error: System.Net.Request is not supported on this platform

How can I set a custom header to my HttpClient request?

CodePudding user response:

You should refer to https://docs.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-5.0&pivots=webassembly

The correct way to make Http requests from a Blazor WebAssembly app is to inject a HttpClient which is designed to work in WASM, not the standard HttpClient.

To add a header, refer to the section (".. with Fetch API request options"](https://docs.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-5.0&pivots=webassembly#httpclient-and-httprequestmessage-with-fetch-api-request-options-1)

requestMessage.Headers.Authorization =
                new AuthenticationHeaderValue("Bearer", token.Value);

requestMessage.Content.Headers.TryAddWithoutValidation(
                "x-custom-header", "value");

CodePudding user response:

Never mind, Blazor WASM is too limited and not adapted for my need, I must rewrite my existing API... I remade my app in blazor server, it works fine.

  • Related