Blazor 项目的 httpClient 不向 WebApi 项目发送请求
Blazor project's httpClient does not send request to WebApi project
我创建了一个自定义解决方案,其中包含一个 Blazor 项目、两个 class 库和一个 WebApi 项目,我为 blazor 和 api 项目配置了两个不同的端口(因为它是不可能使用一个端口),api 应用程序 url 是: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);
...
}
通用服务是一个 class 注入了 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());
我创建了一个自定义解决方案,其中包含一个 Blazor 项目、两个 class 库和一个 WebApi 项目,我为 blazor 和 api 项目配置了两个不同的端口(因为它是不可能使用一个端口),api 应用程序 url 是: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);
...
}
通用服务是一个 class 注入了 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());