【问题标题】:Unable call Web API in Blazor无法在 Blazor 中调用 Web API
【发布时间】:2021-08-24 17:25:24
【问题描述】:

调用 API 时出现以下错误。已测试 API 是否以 JSON 格式返回数据。

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100] 未处理的异常渲染组件:net_http_client_http_browser_baseaddress_required Arg_ParamName_Name, requestUri System.ArgumentException:net_http_client_http_browser_baseaddress_required Arg_ParamName_Name,requestUri 在 System.Net.Http.HttpRequestMessage.InitializeValues(HttpMethod 方法,Uri requestUri) 在 System.Net.Http.HttpRequestMessage..ctor(HttpMethod 方法,Uri requestUri) 在 System.Net.Http.HttpClient.CreateRequestMessage(HttpMethod 方法,Uri uri) 在 System.Net.Http.HttpClient.GetAsync(Uri requestUri,HttpCompletionOption 完成选项,CancellationToken 取消令牌) 在 System.Net.Http.HttpClient.GetAsync(字符串 requestUri,HttpCompletionOption 完成选项,CancellationToken 取消令牌) 在 System.Net.Http.Json.HttpClientJsonExtensions.GetFromJsonAsync[StudentAdmission[]](HttpClient 客户端,字符串 requestUri,JsonSerializerOptions 选项,CancellationToken cancelToken) 在 System.Net.Http.Json.HttpClientJsonExtensions.GetFromJsonAsync[StudentAdmission[]](HttpClient 客户端,字符串 requestUri,CancellationToken cancelToken) 在 BlazorApp1.Pages.FetchData.OnInitializedAsync() 在 Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()

Blazor 页面:
@page "/fetchdata" @inject HttpClient Http

<h1>Weather forecast</h1>

<p>This component demonstrates fetching data from the server.</p>

@if (studentAdmissions == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>FirstName</th>
                <th>LastName (C)</th>
                <th>Gender (F)</th>
                <th>Mobile</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var forecast in studentAdmissions)
            {
                <tr>
                    <td>@forecast.FirstName</td>
                    <td>@forecast.LastName</td>
                    <td>@forecast.Gender</td>
                    <td>@forecast.Mobile</td>
                </tr>
            }
        </tbody>
    </table>
}

@code {
 
    private List<StudentAdmission> studentAdmissions=new List<StudentAdmission>() ;
    protected override async Task OnInitializedAsync()
    {
        studentAdmissions = await Http.GetFromJsonAsync<List<StudentAdmission>>("https://schoolwebapi.azurewebsites.net/api/StudentAdmissions");
    }


    
    public class StudentAdmission
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Gender { get; set; }
        public System.DateTime DateOfBirth { get; set; }
        public string Email { get; set; }
        public string FatherName { get; set; }
        public string Mobile { get; set; }
        public string Standard { get; set; }
        public string PreviousOrganization { get; set; }
        public string CommunicationAddress { get; set; }
        public string PermanentAddress { get; set; }
        public double AdmissionFee { get; set; }
    }
}

**WebApiConfig:**

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace StudnetManagementSystemAPI
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.EnableCors();
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
            config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
        }
    }
}

**Controller:**
    using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using StudnetManagementSystemAPI.Models;
using System.Web.Http.Cors;

namespace StudnetManagementSystemAPI.Controllers
{
    [EnableCors(origins: "http://schoolwebapi.azurewebsites.net", headers: "*", methods: "*")]
    public class StudentAdmissionsController : ApiController
    {




  You can Refer the below Blazor WebAssemly in Azure
    https://blazorapp120210607194704.azurewebsites.net/fetchdata

AzureCors

【问题讨论】:

  • 如果你只是使用Http.GetFromJsonAsync&lt;List&lt;StudentAdmission&gt;&gt;("https://schoolwebapi.azurewebsites.net/api/StudentAdmissions") 呢?
  • 然后会得到一个额外的错误:Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at schoolwebapi.azurewebsites.net/api/StudentAdmissions. (原因:CORS 标头“Access-Control-Allow-Origin”缺失)。
  • 你误解了——access-control-allow-origin 是一个服务器响应头。您需要在某些域的 azure 部署 webapi 的服务器端允许 CORS - 请参阅 social.msdn.microsoft.com/Forums/azure/en-US/…
  • 我也允许 CORS 用于 Web API Azure。仍然出现同样的错误。
  • 好的 - 请更新您的问题以显示您如何在服务器端启用 CORS

标签: c# asp.net-web-api blazor


【解决方案1】:

您的 EnableCors 属性中的来源不正确。您已经获得了 webapi (http://schoolwebapi.azurewebsites.net) 的网址,而它应该是调用它的网站的网址:

[EnableCors(origins: "https://blazorapp120210607194704.azurewebsites.net", headers: "*", methods: "*")]

【讨论】:

  • 太棒了!你能把答案标记为正确吗?
猜你喜欢
  • 1970-01-01
  • 2020-11-10
  • 1970-01-01
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
  • 2020-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多