0

I am developing a Blazor WASM application in .NET6.

In Blazor is possible to make a call from Client component

@code {
   await Http.GetFromJsonAsync<Model>("/api/model/view/" + modelId);
}

that triggers a controller in the Server project

[HttpGet, Route("/api/model/view/{id:int}")]
public async Task<Model> GetModel(int modelId)
{
    try { return await Task.FromResult(_IModel.GetModel(id)); }
    catch { throw; }
}

But is it possible to post from a client project via cs class like following:

HttpClient httpClient = new HttpClient();
var content = new StringContent(JsonConvert.SerializeObject(authcookie_value), Encoding.UTF8, "application/json");
httpClient.BaseAddress = new(Parameters.urlstring);
var result = httpClient.PostAsync("/api/auth/refresh", content);

And the controller on the Server project to be fired:

[HttpPost, Route("/api/auth/refresh")]
public IActionResult AuthRefresh(StringContent httpContent)
{
   try
   {
   }
   catch { throw; }
}

The above example is not working because the controller is not fired when the call is thiggered. Any ideas?

Stavros Koureas
  • 1,126
  • 12
  • 34
  • How are you mapping and using `modelId`? – MrC aka Shaun Curtis Jan 04 '23 at 12:41
  • modelId is an integer, and the first scenario is working – Stavros Koureas Jan 04 '23 at 12:58
  • You're stating that the first scenario works, but that is incorrect. Your URLs won't match. Update the question with the correct endpoint for getting a model via ID. – Marius Jan 04 '23 at 17:49
  • This looks like custom authentication. I suggest using the HTTP header to refresh your session, not a POST HTTP request. Your token should be sent using the headers and stored in a reusable `HttpClient` from `DependencyInjection`. Then on each request to the API you can refresh the token using middleware. – Marius Jan 04 '23 at 17:52
  • @Marius Thanks Marius, indeed i made a mistake while describing the first scenario, I have correct it now. Do you have an example with HTTP header on request for authentication? – Stavros Koureas Jan 05 '23 at 08:58
  • Here are SO links: Add header to `HttpClient`: https://stackoverflow.com/questions/14627399/setting-authorization-header-of-httpclient | Reading the header and a bit extra: https://stackoverflow.com/questions/25855698/how-can-i-retrieve-basic-authentication-credentials-from-the-header | Remember that when it comes to security, you can always learn more and improve. – Marius Jan 05 '23 at 21:09
  • Middleware example, and my suggestion: https://stackoverflow.com/questions/38977088/asp-net-core-web-api-authentication – Marius Jan 05 '23 at 21:10

0 Answers0