Hangfire Job Exception as Failed in .NET 6 - .net-6.0

This is Image where i want to show exception
I want to show my exception in Hangfire (Failed Section) in .NET 6.0. What should I need to do?
I have tried many solution i have also attached my startup file.
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedRedisCache(o =>
{
o.Configuration = Configuration.GetConnectionString("HangRedisConn");
});
services.AddSession();
services.AddRazorPages();
services.AddHealthChecks();
services.AddHangfire(config =>
config.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimpleAssemblyNameTypeSerializer()
.UseDefaultTypeSerializer()
.UseMemoryStorage()
); //add nuget package of memoryStorage
//services.AddHangfire(x => x.UseSqlServerStorage(connString));
services.AddHangfireServer();
services.AddControllers();
services.AddSingleton<IConfiguration>(_config);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IBackgroundJobClient backgroundJobClient)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
//app.UseHangfireDashboard("/hangfire", new DashboardOptions());
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapHangfireDashboard("/hangfire", new DashboardOptions());
});
RecurringJobs.RegisterRecurringJobs(1);
}

Related

InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. (.net core 5)

I use .net 5 web api to create my application.
I put [Authorize] top of my controller.
I use Identityserver4 as auth-server.(localhost:5000)
and here is my startup.cs class:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<MyContext>(opts =>
opts.UseInMemoryDatabase("MyDb"));
services.AddAuthentication("bearer")
.AddIdentityServerAuthentication(opts =>
{
opts.Authority = "http://locallhost:5000";
opts.RequireHttpsMetadata = false;
opts.ApiName = "myApi";
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "CustomerApi", Version = "v1" });
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "CustomerApi v1"));
}
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
but I get below error:
error
please guide me to resolve my problem.
I search much time but the answers is for .net 3.1 .
Your code is ok.
but you should write:
services.AddAuthentication("Bearer")
instead of
services.AddAuthentication("bearer")
After that you might run correctly.
I typically have this setup:
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
I would also not use AddIdentityServerAuthentication (Used by older version of IdentityServer) and instead focus on using AddJwtBearer method instead. See the documentation here

An error occurred applying migrations, try applying them from the command line

I am on visual studio 2019 for mac running a blazor server app with .net core 3.1 and Individual Authentication (In-app) turned on.
When i go to register and enter new users details i am presented with the following error when clicking the apply migrations button
In the appsettings.json i have the following set.
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=Test; user=SA; password=P#55word; Trusted_Connection=False;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using CMUI.Areas.Identity;
using CMUI.Data;
namespace CMUI
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = false)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<IdentityUser>>();
services.AddSingleton<WeatherForecastService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
}
The the SQL server i am running is 2019 mssql in docker using the following command
docker run -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=P#55word' -p 1433:1433 -d --name=mssqlserver2019 mcr.microsoft.com/mssql/server:2019-latest
The database is working okay as i can perform crud actions via an webapi in another solution using the same connection string. Not sure if this is a mac thing or if i have missed something silly.
Thanks.
You can try using the command line and navigating to the project root of the project that connects to that db, and then running dotnet ef database update which should run that migration and build your identity tables. Then fire the app up again and as long as it's connecting (which is looks like you are) you should be able to register users.
Further reading on migrations here. You may need to install the command line tools mentioned in this article.
I'm not familiar with VS for MacOS, but in the windows version you can go to Package Manager Console, make sure the default project in the console is set to your DB access project, and then run the command update-database. This might work for you as well.

Asp.net Core 2.2 app.UseHttpsRedirection() is not defined

When I try to use the app.UseHttpsRedirection() method it gives me a build error saying:
'IApplicationBuilder' does not contain a definition for 'UseHttpsRedirection' and no accessible extension method 'UseHttpsRedirection' accepting a first argument of type 'IApplicationBuilder' could be found (are you missing a using directive or an assembly reference?
I have tried installing the Microsoft.AspNetCore.HttpsPolicy nuget package.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseAbp(); // Initializes ABP framework.
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseCookiePolicy();
app.UseHttpMethodOverride
app.UseJwtTokenMiddleware();
app.UseSignalR(routes =>
{
routes.MapHub<AbpCommonHub>("/signalr");
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "defaultWithArea",
template: "{area}/{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
UseHttpsRedirection is an Extension method hidden in the
Microsoft.AspNetCore.HttpsPolicy DLL. You have to add it (through NuGet or manually)
See the accepted answer here for more DLLs you may need

graphql .NET core solution - unable to include related objects

I am a newbie to graphql, and use it in a .Net core solution. My solution includes an SQlite-database, that may be accessed via a manager. I use the manager in the resolver functions in my GraphTypes. In the models, I have a class 'Ticket' and a class 'TicketResponse' - one ticket includes a list of ticketResponses.
The problem is that I am unable to include the nested data of an ObjectGraphType. Here's my code:
namespace SupportCenter.Schema.GraphQLTypes
{
public class TicketType : ObjectGraphType<Ticket>
{
public TicketType(ITicketManager manager)
{
Name = "Ticket";
Field(x => x.Id, type: typeof(IdGraphType)).Description("The id of the ticket");
Field(x => x.AccountId).Description("THe account the ticket was issued from");
Field(x => x.Text).Description("The description of the problem");
Field(x => x.DateOpened).Description("The date the ticket was opened");
Field<TicketStateEnum>("state", resolve: context => context.Source.State);
Field<ListGraphType<TicketResponseType>>("ticketresponses",
resolve: context => manager.GetTicketResponses(context.Source.Id));
}
}
}
The error I get is the following:
"GraphQL.ExecutionError: No service for type
'GraphQL.Types.ObjectGraphType1[SupportCenter.Schema.GraphQLTypes.TicketType]'
has been registered. ---> System.InvalidOperationException: No service
for type
'GraphQL.Types.ObjectGraphType1[SupportCenter.Schema.GraphQLTypes.TicketType]'
has been registered.\n at
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider
provider, Type serviceType)\n at
GraphQL.Types.Schema.b__56_2(Type type)\n at
GraphQL.Types.GraphTypesLookup.AddTypeIfNotRegistered(Type type,
TypeCollectionContext context)\n at
GraphQL.Types.GraphTypesLookup.HandleField(Type parentType, FieldType
field, TypeCollectionContext context)\n at
GraphQL.Types.GraphTypesLookup.AddType(IGraphType type,
TypeCollectionContext context)\n at
GraphQL.Types.GraphTypesLookup.HandleField(Type parentType, FieldType
field, TypeCollectionContext context)\n at
GraphQL.Types.GraphTypesLookup.AddType(IGraphType type,
TypeCollectionContext context)\n at
GraphQL.Types.GraphTypesLookup.HandleField(Type parentType, FieldType
field, TypeCollectionContext context)\n at
GraphQL.Types.GraphTypesLookup.AddType(IGraphType type,
TypeCollectionContext context)\n at
GraphQL.Types.GraphTypesLookup.Create(IEnumerable1 types,
IEnumerable1 directives, Func2 resolveType, IFieldNameConverter
fieldNameConverter)\n at
System.Lazy1.ViaFactory(LazyThreadSafetyMode mode)\n--- End of stack
trace from previous location where exception was thrown ---\n at
System.Lazy`1.CreateValue()\n at
GraphQL.Types.Schema.get_AllTypes()\n at
GraphQL.Instrumentation.FieldMiddlewareBuilder.ApplyTo(ISchema
schema)\n at GraphQL.DocumentExecuter.ExecuteAsync(ExecutionOptions
options)\n --- End of inner exception stack trace ---",
I have registered both the TicketType and the TicketResponseType in the services in the startup-file. Any ideas what I'm doing wrong?
Here's my startup-file:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSingleton<SupportCenterDbContext>();
services.AddSingleton<TicketType>();
services.AddSingleton<TicketInputCreateType>();
services.AddSingleton<TicketResponseType>();
services.AddSingleton<TicketStateEnum>();
services.AddSingleton<ResponseQuery>();
services.AddSingleton<ITicketManager, TicketManager>();
services.AddSingleton<SupportCentreQuery>();
services.AddSingleton<TicketsQuery>();
services.AddSingleton<TicketsMutation>();
services.AddSingleton<SupportCentreSchema>();
services.AddSingleton<IDependencyResolver>(
c => new FuncDependencyResolver(c.GetRequiredService));
services.AddSingleton<IDocumentExecuter, DocumentExecuter>();
services.AddSingleton<IDocumentWriter, DocumentWriter>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<IGraphQLExecuter<SupportCentreSchema>, DefaultGraphQLExecuter<SupportCentreSchema>>();
services.AddGraphQL(options =>
{
options.EnableMetrics = true;
options.ExposeExceptions = true;
})
.AddWebSockets()
.AddDataLoader();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseGraphQL<SupportCentreSchema>("/graphql");
app.UseGraphiQLServer(new GraphiQLOptions
{
GraphiQLPath = "/ui/graphiql",
GraphQLEndPoint = "/graphql"
});
app.UseMvc();
}
}

How to launch an url on F5 when using Kestrel on a specific port?

I have an Asp.Net Core 2.2 application using Kestrel with default settings. I went in the project's debug properties and set the "Launch Browser" setting to the page I want to start with when debugging and "Launch" to "Project". This all works fine but I want Kestrel to use a specific port. I found plenty of example that work for the port (I use the hosting.json way) but all of them seem to disregard the "Launch Browser" setting.
Is there no way to have Visual Studio automatically open a new window/tab with my chosen URL and use a specific port when I debug?
Program.cs
public class Program
{
public static void Main(string[] args)
{
var host = WebHost.CreateDefaultBuilder(args)
.UseKestrel()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
launchSettings.json
{
"profiles": {
"Kestrel": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger"
}
}
}
hosting.json
{
"urls": "https://localhost:44350/;"
}
and if I'm using hosting.json, my main is:
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddCommandLine(args)
.AddJsonFile("hosting.json", optional: true)
.Build();
var host = WebHost.CreateDefaultBuilder(args)
.UseConfiguration(config)
.UseKestrel()
.UseStartup<Startup>()
.Build();
host.Run();
}
In the project's debug properties , you should set the App URL of "Web Server Settings" to the specific port you want , and the "Launch Browser" is default checked.
Or you chould also set the specific port in the launchSettings.json like below:
"MVC2_2Project": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://localhost:7001;http://localhost:7000"
}
The setting in launchSettings.json and the project's debug properties is synchronous, you can set it up in one place.

Resources