【问题标题】:How to Fix the HTTP PUT & DELET Errors in WebAssembly App如何修复 WebAssembly 应用程序中的 HTTP PUT & DELET 错误
【发布时间】:2021-06-26 22:03:58
【问题描述】:

我已经构建了一个小型 WebAssembly 应用程序来使用 HTTPClient 测试 Web 服务。

  1. 服务器端的 Web 服务是使用 ASP.NET CORE (.NET 5) 构建的。所有 API 均已使用 PostMan 成功测试。
  2. 客户端的 WebAssembly 也是使用 .NET 5 创建的。
  3. 他们都使用 HTTPS。
  4. 已在服务器端启用 CORS。

在 WebAssembly 应用程序中,HttpClient.GetFromJsonAsync 和 HttpClient.PostAsJsonAsync 工作正常。

我在使用 HttpClient.PutAsync、HttpClient.PutAsJsonAsync 或 HttpClient.DeleteAsync 时遇到以下错误。 (测试代码段贴在最后)。

看起来 PUT & DELETE 请求由于某种原因被阻止并且根本没有到达 Web 服务。如果原因是安全,为什么 POST 请求有效。对于如何解决与 PUT & DELETE 相关的问题,我将不胜感激。

错误信息:

Loaded 8.62 MB resources from cache
Loaded 0.06 MB resources from network
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\5.0.4\System.Buffers.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
mono_wasm_runtime_ready fe00e07a-5519-4dfe-b35a-f867dbaf2e28
crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: TypeError: Failed to fetch
System.Net.Http.HttpRequestException: TypeError: Failed to fetch
   at System.Net.Http.BrowserHttpHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.SendAsyncCore(HttpRequestMessage request, HttpCompletionOption completionOption, Boolean async, Boolean emitTelemetryStartStop, CancellationToken cancellationToken)
   at BlazorWebAssembly.Pages.List.HandleDelete(Person p) in C:\Users\yyang\source\repos\Advanced\BlazorWebAssembly\Pages\List.razor:line 72
   at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle)
The thread 0x5624 has exited with code 0 (0x0).
The thread 0x5818 has exited with code 0 (0x0).
The thread 0x1420 has exited with code 0 (0x0).
The thread 0x53b8 has exited with code 0 (0x0).
TEST CODE USING Http.PutAsync

public async Task HandleValidSubmit()
{
    if (Mode == "Edit")
    {
        Person2 p2 = new Person2();
        p2.CopyData(PersonData);

        string data = JsonSerializer.Serialize(p2);
        StringContent centent = new StringContent(data, UnicodeEncoding.UTF8, "application/json");

        HttpResponseMessage response = await Http.PutAsync("/api/people", centent);

        if (!response.IsSuccessStatusCode)
        {
            string statusCode = response.StatusCode.ToString();
            string reason = response.ReasonPhrase;
        }
    }
    else
    {
        await Http.PostAsJsonAsync<Person>("/api/people", PersonData);
    }

    NavManager.NavigateTo("/people");
}

==============================================================================  
TEST CODE USING Http.PutAsJsonAsync

public async Task HandleValidSubmit()
{
    if (Mode == "Edit")
    {
        Person2 p2 = new Person2();
        p2.CopyData(PersonData);

        HttpResponseMessage response = await Http.PutAsJsonAsync<Person2>("/api/people", p2);

        if (!response.IsSuccessStatusCode)
        {
            string statusCode = response.StatusCode.ToString();
            string reason = response.ReasonPhrase;
        }
    }
    else
    {
        await Http.PostAsJsonAsync<Person>("/api/people", PersonData);
    }

    NavManager.NavigateTo("/people");
}
==============================================================================  
TEST CODE USING Http.DeleteAsync

public async Task HandleDelete(Person p)
{
    HttpResponseMessage resp = await http.DeleteAsync($"/api/people/{p.PersonId}");

    if (resp.IsSuccessStatusCode)
    {
        await UpdateData();
    }
    else
    {
        errMsg = resp.ReasonPhrase;
    }
}   

【问题讨论】:

    标签: httpclient blazor-webassembly


    【解决方案1】:

    我遇到的问题通过在 Web 服务应用程序的 startup.cs 文件的 CORS 配置设置中添加“AllowAnyMethod”得到解决:

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

    【讨论】:

      猜你喜欢
      • 2020-11-29
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-14
      • 2013-05-20
      • 1970-01-01
      相关资源
      最近更新 更多