Different mechanism of HttpClient in Blazor server side and Web assembly - asp.net-core

I want to get data from ASP.net Core API with HttpClient Factory.
I use Microsoft.Extensions.Http package like this :
// Register service in IOC containter
builder.Services.AddHttpClient<IProductService, ProductService>(option =>
{
option.BaseAddress = new Uri(""/*Base url*/);
});
// Use in service
var stream = await _httpClient.GetStreamAsync("");
When I use code in Blazor server side and works correctly. But when I use code in Blazor wasm throw Exception
Access to fetch at 'http client factory base url' from origin 'blazor wasm app url' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
No change in ASP.net core API and different results.
I use .net core 3.1 in all apps
Thanks

I activate CORS in my API Like this
// In ConfigureServices method
options.AddPolicy("OpenCors", builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
;
});
// In Configure method
app.UseCors("OpenCors");

Related

ASP.NET Core 6 CORS and Angular 14 problem with published mode

I have an ASP.NET Core 6 project which client side is angular 14 .
I had enable CORS as code below :
var builder = WebApplication.CreateBuilder(args);
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("https://consultation.programmerbox.ir",
"http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
var app = builder.Build();
app.UseCors(MyAllowSpecificOrigins);
when i call the api with postman -> api return value as well as possible, when i call api in client project(development localhost) -> api return value as well as possible , but when publish both client and backend code in diffrent domain i get this error :
Access to XMLHttpRequest at 'https://api.consultation.programmerbox.ir/api/account/sendVerificationCode' from origin 'https://consultation.programmerbox.ir' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
client domain is : https://consultation.programmerbox.ir
and backend domain is : https://api.consultation.programmerbox.ir/
I would be very grateful if you could guide me in this field, I am new in this field
With best regards
picture 1
picture 2

Adding headers to every response of an Blazor WASM in .NET 6

I created a simple (so far) Blazor WebAssembly application in .NET 6.
I'm currently adding additional HTTP requests to every response of the application and wanted to add an X-FRAME-OPTIONS header, but when searching on how to do it, I realized I don't know how to approach it.
For starters here's my Program.cs file:
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using MyApplicationNamespace;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
await builder.Build().RunAsync();
When reading this webpage I learned about using middleware inside
app.Use(async (context, next) =>
{
context.Response.Headers.Add("x-my-custom-header", "middleware response");
await next();
});
I do understand from this site that in order to use the Use function I can do this:
var app = builder.Build();
app.Use();
Or that I can just pass a delegate function
app.Run(async context =>
{
await context.Response.WriteAsync("Hello from 2nd delegate.");
});
Point is, in Blazor WASM I don't have a Run method, and RunAsync does not take parameters.
I'm not sure where to go from here to add a header?
Am I missing a NuGet passage?
From what I've learned from this person on Twitter:
The Blazor WASM application is the client. It lives exclusively within the browser. It is receiving responses from a web server, and not "returning" anything. X-Frame-Options headers need to be set on the server, not by the application in the Browser.
Do you mean that the web server should add these headers when it's delivering the (static) files of your Blazor application to the browser before it starts being executed there? You need to configure your web server (whatever it is) to send these headers then.
Since I deployed my application as an Azure App Service I used Advanced Tools to edit out web.config inspired by this site.

javascript xmlhttp error on signalr in asp.net core

In my application 2 projects and mvc client run at port(5002) and web api project run at port (5001). I have implemented signalr in mvc client. Now showing error log in console as below:
and i have also added configuration to my api project for core policy like:
services.AddCors(options =>
{
options.AddPolicy("signalr",
builder =>
{
builder.WithOrigins("https://localhost:5002")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
And now also showing same error. Please suggest.
You need to configure your CORS like this:
services.AddCors(options =>
{
options.AddPolicy("signalr", builder => builder.WithOrigins("https://localhost:5002")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.SetIsOriginAllowed((host) => true));
});
The lambda function that you pass to the .SetIsOriginAllowed() method returns true if an origin is allowed, so always returning true allows any origin to send requests to the api. The allow origin access control http header returned when using this method contains the origin that sent the request, not a wildcard, e.g. Access-Control-Allow-Origin: http://localhost:4200.

CORS Error on Uno WebAssembly with ASP..NET Core REST API Service

I got these error on WebAssembly with Uno Platform.
Access to fetch at 'https://localhost:44318/api/search/bebek/TR' from
origin 'http://localhost:49917' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
I got some data responses as a JSON file from API service. The UWP app do it without error:
//_savedSearchList = await _dbService.SearchAsync(_keyword, _sentLanguageArgument); // Normal database connection for UWP.
//_savedSearchList = await _dbService.SearchAsync(_keyword, _sentLanguageArgument); // Normal database connection for UWP.
//Get search list for webservice.
var link_search = $"https://localhost:44318/api/search/{_keyword.ToLower()}/{_sentLanguageArgument}";
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(link_search);
Debug.WriteLine($"Http Status Code for Connection: {response.StatusCode}");
if (response.IsSuccessStatusCode)
{
var jsonString = await response.Content.ReadAsStringAsync();
_savedSearchList = JsonConvert.DeserializeObject<List<SearchResultCapsule>>(jsonString).OrderBy(t => t.IssueNumber);
if (_savedSearchList.Count() != 0)
{
ResultList.ItemsSource = _savedSearchList;
NoResult_Grid.Visibility = Visibility.Collapsed;
}
}
}
What is the real problem on WebAssembly ? And how can I fix it ? Thanks.
This is a security restriction from the Javascript fetch API, where the endpoint you're calling needs to provide CORS headers to work properly.
If you control the API, you'll need to use the features from your framework to enable CORS, and if you don't you'll need to ask the maintainers of the endpoint to enable CORS.
To test if CORS is really the issue, you can use CORS Anywhere to proxy the queries.
It solved via Microsoft CORS package. Thanks.

how to use session on asp.net core 2.2 and vue with jwt authentication

i use vue js 2 and asp.net core 2.2 on my project
I use origin cors on my app and set my vue js development address to WithOrigins and on front side set {withCredentials: true } on very request
services.AddCors(o => o.AddPolicy("AllowAll", builder =>
{
builder
.WithOrigins("http://localhost:8080")
.AllowCredentials()
.AllowAnyMethod()
.AllowAnyHeader();
}));
set startup to use session properly like this
on ConfigureServices
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(10);
});
and use it
app.UseSession("AllowAll");
when authentication successfully with front side I must save loged in user on session and other request I need to save object on session and return on another request .
I try to setString - setting and ... but when I send another request the session id changes per request and I not able to get what set on last session .
any idea for another way to save status of user on something like session?
I used ImemoryCache but I don't know abou life cycle or is generate unique id for every user ?
any way to use session ?( I know the restful api communicate with token but I need that )