【问题标题】:Blazor Web Assembly consume API which requires authorization Visual Studio 2019Blazor Web Assembly 使用需要授权 Visual Studio 2019 的 API
【发布时间】:2020-12-18 21:32:13
【问题描述】:

我创建了一个 Blazor WASM 项目,以便使用需要授权的第三方 REST API。过去,这种将标头值用于TestClient.DefaultRequestHeaders.Authorization 的方法已经奏效。但是,在 Blazor 中,这种编码方法每次都会返回一个 Http 403 代码。我知道查询和凭据在 Postman 中是有效的。这是“Index.razor”代码,我想在其中查看 JSON 返回的字符串以进行分析:

@page "/"
@inject HttpClient TestClient

<h3>Presentations Scheduled</h3>

<form>
    <fieldset class="form-group">
        <div>
            <button type="button" class="btn btn-dark mr-sm-2 mb-2"
                    @onclick=@(async ()=>  await GetToday())>Today
            </button>
        </div>
    </fieldset>

    @if (string.IsNullOrWhiteSpace(errorString) == false)
    {
        <div class="h2">@errorString</div>
    }
    else
    {
       <div class="h2">@httpResponse</div>
    }
</form>
   
@code
{
    string errorString;
    string httpResponse;

    private async Task GetToday()
    {
        var byteArray = Encoding.ASCII.GetBytes("user:pass");                
        TestClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",Convert.ToBase64String(byteArray));
        string todayDate = DateTime.Today.AddDays(0).ToString("yyyyMMdd");
        string TestbaseURL = "https://webservices.XXXAPI.com/";
        UriBuilder TestURI = new UriBuilder(TestbaseURL);
        TestURI.Scheme = "https";
        TestURI.Path = "ws/run/reservations.json";
        TestURI.Query = "resource_query_id=244782";
        var Testquery = HttpUtility.ParseQueryString(TestURI.Query);
        Testquery["scope"] = "extended";
        Testquery["start_dt"] = todayDate;
        Testquery["end_dt"] = todayDate;
        TestURI.Query = Testquery.ToString();
        TestbaseURL = TestURI.ToString();

        try
        {
            httpResponse = await TestClient.GetStringAsync(TestbaseURL);
            errorString = null;
        }
        catch (Exception ex)
        {
            errorString = $"There was a problem: {ex.Message}";
        }   
    }
}

【问题讨论】:

  • 更新 - 我在提出请求时将此问题追溯到 CORS 问题 - 我看到“CORS Missing allow origin”所以我正在寻找解决此问题的方法

标签: c# rest authorization visual-studio-2019 blazor


【解决方案1】:

我已将问题缩小到我的 Blazor WASM 应用程序的 CORS 问题,因此我将回答这个问题并开始一个新的更有针对性的问题。

【讨论】:

    猜你喜欢
    • 2019-12-04
    • 2020-12-16
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    • 2019-11-03
    • 1970-01-01
    • 2020-06-26
    • 2021-05-20
    相关资源
    最近更新 更多