I’m unable to get data from .Net 6 API into Blazor WASM app.
Firefox shows the on the bottom the very often mentioned error:
I worked on this tutorial:
https://learn.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-6.0&pivots=webassembly
To fix the CORS Problem I read this document:
https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-6.0
I have no idea what I doing wrong. Please can someone have I look in my demo app on GitHub? I created a simple demo app.
https://github.com/Christoph1972/BlazorTestGetAPIData
for CORS you can do this:
options.AddPolicy("CorsPolicy", builder => builder.WithOrigins("http://<YOUR_URL>")//The client Url that wants to get data
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.SetIsOriginAllowed((host) => true));
and
var app = builder.Build();
app.UseHttpsRedirection();
app.UseCors("CorsPolicy"); <-----
Related
I'm trying to configure IdentityServer4 in a .Net Core 3 project.
My ConfigureServices-Method looks like this:
services.AddIdentityServer()
.AddSigningCredential(new X509Certificate2(#"*redacted*", "*redacted*"))
.AddTestUsers(InMemoryConfiguration.GetUsers().ToList())
.AddConfigurationStore(builder => builder.UseSqlServer(...))
Unfortunately, the builder.UseSqlServer(...) which used to work in earlier versions is not available anymore.
What is the correct way to configure IdentityServer4 to use an SQL Server nowadays?
Thanks in advance
Try this
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = b =>
b.UseSqlServer(...);
})
We have a legacy application built in Classic ASP that needs to access an API - this API is "protected" by an IdentityServer - so basically we need to implement OpenIdConnect support for this legacy application.
By far the easiest solution I can think of is trying to wrap this site somehow in a more updated version, then we could just add a few lines of code in the Owin-startup and everything should(?) be fine by adding:
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = "Cookies";
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.ClientId = "mvc";
options.ClientSecret = "secret";
options.ResponseType = "code id_token";
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Add("api1");
options.Scope.Add("offline_access");
});
So it is possible to somehow get OWIN to work with Classic ASP? Or are we doomed to try and built our own client/middleware?
If there is no other "show-stopper" preventing you to update to .Net Framework 4.5.1+, than this is your right solution.
If you go to the Owin official NuGet page it will show you, that the library particularly has no dependencies, BUT this is not quite correct.
If we go to the source of the Microsoft.Owin we will see:
<TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>
So it actually depends on .Net Framework 4.5.1. If you have the possibility to upgrade your project - do it.
I am doing POC using Prometheus in .net core app. I did not found sufficient information on Prometheus website to get started , I have following question if someone can answer that would be helpful
a) Do I need to write my own .net core client in order to use
prometheus in app?
b) What is best approach to use prometheus for metric recording such as
should I use in every client or add prometheus logging logic in
services method so that metrics is logged for each request and
response in pipeline ?
c) where to configure prometheus server in .net core app ?
Monitor .Net core web API using prometheus
Install the below packages
<PackageReference Include="App.Metrics.AspNetCore" Version="3.2.0" />
<PackageReference Include="App.Metrics.AspNetCore.Endpoints" Version="3.2.0" />
<PackageReference Include="App.Metrics.AspNetCore.Tracking" Version="3.2.0" />
<PackageReference Include="App.Metrics.Formatters.Prometheus" Version="3.2.0" />
Add the below code in Program.cs class to support prometheus
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseMetricsWebTracking()
.UseMetrics(option =>
{
option.EndpointOptions = endpointOptions =>
{
endpointOptions.MetricsTextEndpointOutputFormatter = new MetricsPrometheusTextOutputFormatter();
endpointOptions.MetricsEndpointOutputFormatter = new MetricsPrometheusProtobufOutputFormatter();
endpointOptions.EnvironmentInfoEndpointEnabled = false;
};
})
.UseStartup<Startup>();
Make sure these below endpoints are working after making all the above changes
http://<ip:port>/metrics
http://<ip:port>/metrics-text
Add a new job in prometheus.yml
- job_name: 'SampleWebAPi'
metrics_path: /metrics-text
static_configs:
- targets: ['<ip:port>']
Restart prometheus & then check targets page
http://localhost:9090/targets
Github Code
.net client for prometheus.io now supports.NET Core 2.0:
https://github.com/prometheus-net/prometheus-net
Client is suggested here: https://prometheus.io/docs/instrumenting/clientlibs/
We are using our own open source library because no other existing solution worked correctly at the time we started using Prometheus.
https://github.com/nexogen-international/Nexogen.Libraries.Metrics
This library can add a lot of metrics out-of-the box. I recommend measuring everything you can as you can never know what will be a bottleneck in production. At least measure everything that can be a key performance indicator, like number of visitors or the time it takes to do some long operation.
The library can be configured in your ASP.NET Core Startup. I recommend injecting your metrics through an interface containing your relevant metrics.
If you have a non ASP.NET app, then you can simply set it up in your main class.
Use the this nuget library if you are using dotnet core. This will give lot of metrics out of the box.
In Configure method of startup.cs.
add app.UseHttpMetrics() after app.UseRouting. Futhermore add endpoints.MapMetrics(); as end point which expose end point to scrap prometheus metrics
Sample project here:
Repo: https://github.com/CodeSam621/YT_DotNetCorePrometheusGrafana
app.UseRouting();
app.UseHttpMetrics();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapMetrics();
endpoints.MapControllers();
});
https://www.youtube.com/watch?v=cvt1Vrs3ajU
Locally my project runs fine but when I deploy on Azure using a web app, I get the following error when it starts:
MissingMethodException: Method not found: 'Newtonsoft.Json.JsonSerializerSettings Microsoft.AspNet.Mvc.Formatters.JsonOutputFormatter.get_SerializerSettings()'.
SmartAdmin.Startup.<>c.b__13_7(MvcOptions options)
I've tried this:
services.AddMvc(options =>
{
options.Filters.Add(new UserPreferencesLoaderAtrribute());
var jsonFormatter = (JsonOutputFormatter)options.OutputFormatters.FirstOrDefault(f => f is JsonOutputFormatter);
if (jsonFormatter != null)
{
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
});
And this:
services.AddMvc(options =>
{
options.Filters.Add(new UserPreferencesLoaderAtrribute());
}).AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
Yes, I just worked all night and did eventually figured it out. Here is what you need to do:
Make sure you install:
-Microsoft.AspNet.Mvc.Formatters.Json version "6.0.0-rc1-final"
and
-Revert Netonsoft.Json to "6.0.6".
Then you can keep this:
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
project.json:
"Microsoft.AspNet.Mvc.Formatters.Json": "6.0.0-rc1-final",
"Newtonsoft.Json": "6.0.6"
I had a bunch of trouble redeploying too but eventually this worked.
Good luck!
Just got off a call with Microsoft support as of yesterday (02 Aug 2016) Azure App Services now only support ASP.NET core, due to a breaking change:
A breaking change was released and anything other than ASP.NET core is not supported, so the only option is an upgrade. The breaking change is being rolled out to all (regions) eventually all your instances will fail.
Is ASP.NET 5, Core RC1, RC2 supported on Azure App Service? NO
https://blogs.msdn.microsoft.com/waws/2016/06/14/supporting-asp-net-5-core-rc1-on-azure-app-service/
Verify your app is running the latest version of ASP.NET Core and not RC1 or RC2.
We were affected (North Europe) and upgraded our app from RC2 and it worked first time.
We also saw this in production, contacted the team and got this out: https://social.msdn.microsoft.com/Forums/en-US/f0a6bbaf-498a-4c1f-b869-6779ee18e04e/app-service-applications-may-experience-methodnotfound-exceptions-due-to-incorrect-newtonsoft-json?forum=windowsazurewebsitespreview
It appears that a fix for App Service is on its way as well. Meanwhile, the linked post contains pretty much the same instructions as the other answers here.
I'm exploring ASP.NET Core Web Applocation empty template. And I'm little bit confused there: if I run the application created by VS new project wizard with no changes and break point on WriteAsync method I could see that it runs two times.
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
Does anybody know if this is normal behaviour or a kind of bug?
You can use logging for diagnosing these kind of issues. You can use the Debug logger to see the log messages in the debug output window.
Add the package Microsoft.Extensions.Logging.Debug to your project.json and do the following in Startup.cs's Configure method:
loggerFactory.AddDebug()
Regarding why you are seeing 2 times, I guess one of the requests is for the fav.ico from the browser.