2

I have a controller on the server side looking like this:

 [HttpGet]
    public IActionResult Test(string returnUrl = "/")
    {
        return Challenge(new AuthenticationProperties() { RedirectUri = returnUrl });
    }

And when I press a button on the client side i call:

await Http.GetAsync("/api/Login/Test");

The problem is that I'm getting a cors error in the console and nothing happens. If i put in the url manually in the browser (localhost/api/Login/test) it works fine.

I added a cors policy that looks like this:

services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());
        });

and

 app.UseCors("CorsPolicy");

Which didn't make a difference.

user3713080
  • 205
  • 2
  • 12

2 Answers2

1

Use this: await Http.GetJsonAsync<put here your return type>("/api/Login/Test");

This is the method signature:

public static async Task<T> GetJsonAsync<T>(this HttpClient httpClient, string requestUri)

Note: You should use the methods defined in the HttpClientJsonExtensions class. These methods are configured to make Ajax requests to your Web API, using the JavaScript Fetch Web API, and more importantly, they are aware of the base uri of your application (<base href="/">)

See https://github.com/aspnet/AspNetCore/blob/5a70f5312fb57fc3788e5af56a99e7b43761e195/src/Components/Components/src/HttpClientJsonExtensions.cs

Hope this helps...

enet
  • 26,272
  • 2
  • 38
  • 70
  • The return type would be IActionResult which I can't access from the client (to my knowledge) as it's part of Microsoft.AspNetCore.Mvc. Unless I add the nuget package but I feel like I'm taking the wrong route doing that – user3713080 Mar 12 '19 at 19:25
  • What do you want to return ? You are using get async, right ? You want to get something... what do you want to get ? What do you want to do ? – enet Mar 12 '19 at 20:12
  • I want to do something that would equal ```Log In``` – user3713080 Mar 12 '19 at 20:22
1

Solved it by using

@inject Microsoft.AspNetCore.Components.Services.IUriHelper UriHelper

and

 UriHelper.NavigateTo("/api/Login/Test", forceLoad: true);
user3713080
  • 205
  • 2
  • 12