Blazor项目的httpClient不向WebApi项目发送请求

问题描述

我创建了一个自定义解决方案,其中包含Blazor项目,两个类库和一个WebApi项目,我为blazor和api项目配置了两个不同的端口(因为无法使用一个端口),api应用程序的网址为:http :// localhost:36855 /,我将可用的blazor wasm(解决方案中包含3个项目的标准Microsoft模板)文件复制到了这些项目,并希望它们能够正常工作,Api项目可以运行,并且我可以用邮递员测试其操作方法, Blazor项目也可以运行,但是无法将请求发送到webapi项目,例如在我具有的登录页面中:

private async void HandleValidSubmit()
{        
    AjaxLoading = true;
    disableLoginButton = true;
    ReturnModel = await genericService.PostModelAsyncOld<LoginModel>("api/Account/Login",Model);
    ...
}

通用服务是一个将httpclient注入其中的类,它的任务是与服务器以及Get和Post方法联系(它在我在此处复制的项目中起作用):

public class GenericService : IGenericService
{
    private HttpClient httpClient;
    public GenericService(HttpClient httpClient)
    {
        this.httpClient = httpClient;
        //this.httpClient.BaseAddress = new Uri("http://localhost:36855/");
    }

    public async Task<AsyncReturn<TModel>> PostModelAsyncOld<TModel>(string uri,TModel model)
    {
        TModel returnModel = default(TModel);
        
        HttpResponseMessage result =
            await httpClient.PostAsync(uri,new StringContent(JsonConvert.SerializeObject(model),Encoding.UTF8,"application/json"));                                                     
        if (result.IsSuccessstatusCode)
        {                
            returnModel = JsonConvert.DeserializeObject<TModel>(result.Content.ReadAsstringAsync().Result);                ;                
            return new AsyncReturn<TModel>()
            { AsyncSuccess = true,Model = returnModel,StatusCode = System.Net.HttpStatusCode.OK };
        }
        else
        {                
            return new AsyncReturn<TModel>()
            { AsyncSuccess = false,Model = default(TModel),StatusCode = result.StatusCode };
        }

    }
 }

api控制器和操作方法(仅适用于PostMan,不适用于HttpClient):

[ApiController]
[Route("api/[controller]")]   
public class AccountController : Controller
{
    .... 
    // inject services and other methods 
    ....

    [HttpPost]
    [Route("Login")]
    public async Task<LoginModel> Login(LoginModel model)    //,string returnUrl,string culture)
    {
        if (ModelState.IsValid) // **Breakpoint here,only hits with PostMan not by Blazor ApP**
        {
          ....

我还去了program.cs并进行了更改:

public class Program
{
    public static async Task Main(string[] args)
    {
        var builder = WebAssemblyHostBuilder.CreateDefault(args);
        builder.RootComponents.Add<App>("app");
        
        // The following line is the change:
        builder.Services.AddSingleton(sp => new HttpClient() { BaseAddress = new Uri("http://localhost:36855/") });           //builder.HostEnvironment.BaseAddress) });

        builder.Services              
          .AddHttpContextAccessor()
          .AddScoped<HttpContextAccessor>()
          .AddSingleton<ITokenService,TokenService>()
          .AddSingleton<IGenericService,GenericService>()
          .AddSingleton<ViewDataService>()              
          .AddblazoredSessionStorage();

我尽了一切努力使这项工作奏效,但没有成功,这是什么问题?

解决方法

在通过F12查看Blazor错误消息后,我意识到CORS导致了此问题,因此我在启动文件中的ConfigureServices和Configure方法中添加了以下代码行:

services.AddCors();

app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());