Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor HttpRequestException:TypeError:Failed to fetch

I have a blazor application and trying to post a record via .net core api. When I make a post request blazor throws an error: HttpRequestException: TypeError:Failed to fetch at system.Net.HttpClient.SendAsyncCore(HttpsRequestMessagé request,HttpCompletionOption completionOption,boolean async,Boolean async,Boolean emitTelemetryStartStop, Cancellation Token cancellationToken)

since I'm pretty new to blazor and api, can't figure out where the problem is.

.net core Web api controller

[ApiController]
[Route("api/[controller]/[action]")]
[HttpPost]
Public async Task <IactionResult> AddColumn ([FromQuery]Column column)
{
 var response=await _repository.Insert (column)
return Ok (response)
}

Blazor application;

private async void AddNewColumn ()
{
Column column=new Column {Name="eric",Isvisible=true,Order=10};
var response=await Http.PostAsJsonAsync<Column>("/api/Column/AddColumn",column);
}

I tested AddColumn method on swagger and it works perfectly fine. Also I don't get any errors while trying to get records via api which makes me ensure that the issue is not related with base adress. I'm waiting for your helps.

like image 225
Adam Wick Avatar asked Nov 01 '25 11:11

Adam Wick


1 Answers

In the web api project, do the following.

If you have Startup.cs file, then find the configure method and add the following in the very beginning of the method(not in the end, it wont work).

public virtual void Configure(IApplicationBuilder app)
{
  // Add the following right in the beginning.
  app.UseCors(x => x
    .AllowAnyMethod()
    .AllowAnyHeader()
    .SetIsOriginAllowed(origin => true) // allow any origin  
    .AllowCredentials());               // allow credentials 

  // Other config will come after this.
}

If you are in the latest .net 6 and above project types, then open the program.cs.

In there you add the same code as above. It should look as follows.

var app = builder.Build();

app.UseCors(x => x
    .AllowAnyMethod()
    .AllowAnyHeader()
    .SetIsOriginAllowed(origin => true) // allow any origin  
    .AllowCredentials());               // allow credentials 
like image 170
VivekDev Avatar answered Nov 04 '25 01:11

VivekDev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!