【问题标题】:Blazor oauth2 blocked by CORSBlazor oauth2 被 CORS 阻止
【发布时间】:2019-08-03 08:01:44
【问题描述】:

我在服务器端有一个控制器,如下所示:

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

当我按下客户端的按钮时,我会调用:

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

问题是我在控制台中遇到了 cors 错误,但什么也没发生。如果我在浏览器(localhost/api/Login/test)中手动输入 url,它工作正常。

我添加了如下所示的 cors 策略:

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

 app.UseCors("CorsPolicy");

这并没有什么不同。

【问题讨论】:

    标签: asp.net-core oauth-2.0 cors blazor


    【解决方案1】:

    使用这个:await Http.GetJsonAsync<put here your return type>("/api/Login/Test");

    这是方法签名:

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

    注意:您应该使用 HttpClientJsonExtensions 类中定义的方法。这些方法被配置为使用 JavaScript Fetch Web API 向您的 Web API 发出 Ajax 请求,更重要的是,它们知道您的应用程序的基本 uri (&lt;base href="/"&gt;)

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

    希望这会有所帮助...

    【讨论】:

    • 返回类型将是 IActionResult,我无法从客户端访问(据我所知),因为它是 Microsoft.AspNetCore.Mvc 的一部分。除非我添加了 nuget 包,但我觉得我这样做是走错路了
    • 您要返回什么?您正在使用获取异步,对吗?你想得到什么……你想得到什么?你想做什么?
    • 我想做一些等于&lt;a asp-action="Test" asp-controller="Login" class="btn btn-default"&gt;Log In&lt;/a&gt;
    【解决方案2】:

    通过使用解决它

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

     UriHelper.NavigateTo("/api/Login/Test", forceLoad: true);
    

    【讨论】:

      猜你喜欢
      • 2019-11-30
      • 1970-01-01
      • 2020-11-11
      • 2021-01-10
      • 1970-01-01
      • 1970-01-01
      • 2020-11-04
      • 2020-09-11
      • 2021-04-16
      相关资源
      最近更新 更多