简体   繁体   中英

Unable call Web API in Blazor

Getting the below error when I Call API. Have tested that the API is returning data in JSON.

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100] Unhandled exception rendering component: net_http_client_http_browser_baseaddress_required Arg_ParamName_Name, requestUri System.ArgumentException: net_http_client_http_browser_baseaddress_required Arg_ParamName_Name, requestUri at System.Net.Http.HttpRequestMessage.InitializeValues(HttpMethod method, Uri requestUri) at System.Net.Http.HttpRequestMessage..ctor(HttpMethod method, Uri requestUri) at System.Net.Http.HttpClient.CreateRequestMessage(HttpMethod method, Uri uri) at System.Net.Http.HttpClient.GetAsync(Uri requestUri, HttpCompletionOption completionOption, CancellationToken cancellationToken) at System.Net.Http.HttpClient.GetAsync(String requestUri, HttpCompletionOption completionOption, CancellationToken cancellationToken) at System.Net.Z9D4D43DE68F0B3 555D5A5EF5DC05BB95Z.Json.HttpClientJsonExtensions.GetFromJsonAsync[StudentAdmission[]](HttpClient client, String requestUri, JsonSerializerOptions options, CancellationToken cancellationToken) at System.Net.Http.Json.HttpClientJsonExtensions.GetFromJsonAsync[StudentAdmission[]](HttpClient client, String requestUri, CancellationToken cancellationToken) at BlazorApp1.Pages.FetchData.OnInitializedAsync() at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()

Blazor Page:
@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

Your origins isn't correct in your EnableCors attribute. You've got the url of your webapi ( http://schoolwebapi.azurewebsites.net ) when it should be the url of the website calling it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM