由于新的.net 3.2预览版不再具有带有configureServices函数的startup.cs,因此我无所适从,不知道如何实现.AddCors。添加服务的旧方法实质上是先添加然后使用服务。看起来这不再是解决问题的方法。添加CORS的正确代码是什么?
Program.cs
using System.Threading.Tasks;
using Microsoft.AspNetCore.Blazor.Hosting;
using Microsoft.Extensions.DependencyInjection;
using BlazorDemo.Shared;
namespace BlazorDemo
{
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services.AddSingleton<IDataLayer, DataLayer>();
builder.Services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder
.AllowAnyOrigin());
});
builder.RootComponents.Add<App>("app");
await builder.Build().RunAsync();
}
}
}
Data.cs
namespace BlazorDemo.Shared
{
public class Data
{
public Country[] data { get; set; }
}
}
DataLayer.cs
using System;
using System.Threading.Tasks;
using System.Net.Http;
using Microsoft.AspNetCore.Components;
namespace BlazorDemo.Shared
{
public interface IDataLayer
{
Task<Country[]> FetchCountries(string sortField, bool sortDesc);
Task<Country[]> FetchCountries();
}
public class DataLayer : IDataLayer
{
public DataLayer(HttpClient httpClient)
{
this.httpClient = httpClient;
}
HttpClient httpClient;
public async Task<Country[]> FetchCountries(string sortField, bool sortDesc)
{
var url = $"http://outlier.oliversturm.com:8080/countries?sort[0][selector]={sortField}&sort[0][desc]={sortDesc}&take=10";
var data = await httpClient.GetJsonAsync<Data>(url);
return data.data;
}
public async Task<Country[]> FetchCountries()
{
Country[] Countries;
try
{
var url = $"http://outlier.oliversturm.com:8080/countries";
var data = await httpClient.GetJsonAsync<Data>(url);
Countries = ((Data)data).data;
}
catch (Exception e)
{
Country c = new Country() { name = "DD", areaKM2 = 2, population = 50, _id = e.Message };
Countries = new Country[] { c };
}
return Countries;
}
}
}