i have a problem running my Asp.net core site on Debian 8 using netcore 1.1.1 with version 1.0.3
So i made a site using Asp.net core on my windows 10 platform using VS2017 and published it by dotnet publish -c release
Then i uploaded my project using FTP to Debian 8 and then i wrote
dotnet Altram.Web.Donate.dll
Unhandled Exception: System.InvalidOperationException: AddIdentity must be called on the service collection.
at Microsoft.AspNetCore.Builder.BuilderExtensions.UseIdentity(IApplicationBuilder app)
at Altram.Web.Donate.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) in /mnt/d/Development/C#/Visual Studio/Altram System/Altram.Web.Donate/Startup.cs:line 104
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
at Altram.Web.Donate.Program.Main(String[] args) in /mnt/d/Development/C#/Visual Studio/Altram System/Altram.Web.Donate/Program.cs:line 10
Aborted
in Startup.cs at ConfigureServices method i have
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
if (Environment.IsDevelopment())
{
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Info());
options.IncludeXmlComments(Path.Combine(PlatformServices.Default.Application.ApplicationBasePath,
"Altram.Web.Donate.xml"));
});
services.AddDbContext<DatabaseContext>(builder =>
{
builder.UseNpgsql(Configuration["Data:AltramDatabase"],
options => options.MigrationsAssembly("Altram.Web.Donate"));
});
services.AddDbContext<DatabaseContextCache>(builder =>
builder.UseInMemoryDatabase());
services.AddIdentity<User, IdentityRole>()
.AddEntityFrameworkStores<DatabaseContext>()
.AddErrorDescriber<ErrorDescriber>()
.AddDefaultTokenProviders();
services.Configure<IdentityOptions>(options =>
{
options.Password.RequiredLength = 46;
});
services.AddMvc();
services.AddDataInitializer();
services.DomainInitializer();
services.Initialize(links =>
{
links.Login = Configuration["Robokassa:RobokassaLogin"];
links.Mode = Configuration["Robokassa:RobokassaMode"];
links.Pass1 = Configuration["Robokassa:RobokassaPass1"];
links.Pass2 = Configuration["Robokassa:RobokassaPass2"];
});
services.AddLogging();
}
}
and Configure Method
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseIdentity();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
So it give me that error at app.UseIdentity(); Line
and it's working very good without any problems on Windows 10.
I use PostgresSql with my project.
How can i fix this problem?
I have fixed my error by removing and put it outside of the if brackets
services.AddIdentity<User, IdentityRole>()
.AddEntityFrameworkStores<DatabaseContext>()
.AddErrorDescriber<ErrorDescriber>()
.AddDefaultTokenProviders();
From the if(Enviroment.IsDevelopment()) code because when i start dotnet from the terminal it starts at production Enviroment mode, so addIdentity won't work.
Related
I have a .Net 5.0 API project that stopped working after some recent changes. As there were many changes I still haven't found the reason for the problem that is causing this error:
"InvalidOperationException: EndpointRoutingMiddleware matches endpoints setup by EndpointMiddleware and so must be added to the request execution pipeline before EndpointMiddleware. Please add EndpointRoutingMiddleware by calling 'IApplicationBuilder.UseRouting'"
Startup.cs Basic Code:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddAutoMapper(typeof(Startup));
var mapperConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new MappingProfile());
});
IMapper mapper = mapperConfig.CreateMapper();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseExceptionHandler("/error");
app.UseAuthorization();
app.UseAuthentication();
app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
There is a missing app.UseRouting(); line in the Configure method. Put it before app.UseAuthorization(); line, as per guidelines.
I'm building a brand new ASP.Net Core MVC project. When I try to run it in the debugger, I get this error:
System.IO.IOException
HResult=0x80131620
Message=Failed to bind to address https://localhost:5001.
Source=Microsoft.AspNetCore.Server.Kestrel.Core
StackTrace:
at Microsoft.AspNetCore.Server.Kestrel.Core.LocalhostListenOptions.<BindAsync>d__2.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
This exception was originally thrown at this call stack:
[External Code]
Inner Exception 1:
AggregateException: One or more errors occurred. (An invalid argument was supplied.) (An invalid argument was supplied.)
Inner Exception 2:
SocketException: An invalid argument was supplied.
The error occurs in my Program.cs class:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run(); //<-- ERROR BREAKS HERE
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
I found this SO post getting a similar issue, however my problem is not that the address is already in use, and I am not on a mac. I have updated to the most recent VS version, 17.1.0 at time of writing, but the error persists.
Can anyone offer advice?
EDIT: I tried using the localhost port numbers that were assigned to the application at create time, 7161 and 5161, and I get the same error: "SocketException: An invalid argument was supplied."
I've also tried opening the port in Windows Firewall. No change.
EDIT 2: Here's the code in Startup.cs as well.
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.AddHttpClient();
services.AddControllersWithViews();
// declare external services and database contexts
services.AddDistributedMemoryCache();
services.AddHsts(options =>
{
options.Preload = true;
options.IncludeSubDomains = true;
options.MaxAge = TimeSpan.FromDays(1);
});
// Adds the HTTPS Redirect
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
options.HttpsPort = 5001;
});
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(20);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
options.Cookie.Name = "GLEntry.Authentication";
});
// Add IHttpContextAccessor
services.AddHttpContextAccessor();
services.AddMvc();
// May need this for application authentication?
services.AddAuthentication(IISDefaults.AuthenticationScheme);
}
// 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();
}
else
{
app.UseExceptionHandler("/Home/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.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
See https://stackoverflow.com/a/70915818/13242440
In the command line, on behalf of the administrator:
net stop winnat
net start winnat
So this makes absolutely no sense, but I was able to get it working by setting the debugger to use "IIS Express", instead of the project name. It's the dropdown next to the green "play" button in VS; not sure what that setting's called.
Anyway, that fixed it for me.
I am using .NET Core 3.0 and suddenly I am getting error below, yes it was working fine last week:-
Nonetheless something has changed and I can't workout what - seems to be related to a directory being wrong.
I have deleted the .vs hoping it would work after it is regenerated...
I have followed below links but to no avail...
HTTP Error 500.30 - ANCM In-Process Start Failure
Reading and using appsettings.json in Program.cs?
https://forums.asp.net/t/2159371.aspx?Application+LM+W3SVC+10+ROOT+failed+to+start+process+ErrorCode+0x80070005+
Dotnet Core Multiple Startup Classes with In-Process Hosting
The Event Viewer shows:-
Adding StartUp.cs
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.AddMvc();
services.AddAuthorization(options =>
{
options.AddPolicy("ADGroup", policy =>
policy.Requirements.Add(new UserHelper.CheckAdGroupRequirement(Configuration["SecuritySettings:ADGroup"])));
});
services.AddSingleton<IAuthorizationHandler, UserHelper.CheckAdGroupHandler>();
services.AddHttpContextAccessor();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error/{0}");
// 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.MapRazorPages();
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
A nudge in the right direction would be highly appreciated....
So, I am trying to migrate my ASP.NET Core project to 3.0, and am having some breaking changes. I am trying to use OpenID Connect with AWS Cognito to authenticate users to the web application. Worked fine in my 2.2 project, but no longer works with 3.0 (preview 9).
This is the error I receive:
An unhandled exception has occurred while executing the request.
System.ArgumentNullException: context (Parameter 'Value cannot be null or empty.')
at Microsoft.AspNetCore.Mvc.Routing.UrlHelperFactory.GetUrlHelper(ActionContext context)
It seems as though my IActionContextAccessor is now null when trying set this up.
IActionContextAccessor is injected in an AuthenticationBuilder function.
I am not sure what might be the issue.
In my startup.cs in the Configure function I have the following:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UsePathBase("/");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/error/500/");
}
app.UseStatusCodePagesWithRedirects("/error/{0}/");
app.UseAuthentication();
if (env.IsProduction())
{
app.Use((context, next) =>
{
// https://github.com/aspnet/Security/issues/757
context.Request.Scheme = "https";
return next();
});
}
app.UseStaticFiles();
app.UseRouting();
//app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Endpoints}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
I have also included this in my .csproj:
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="3.0.0-preview9.19424.4" />
Is there some weird thing I'm now missing?
I'm fairly new to web development so I've been experimenting with the template code Microsoft has provided through their default .NET Core Application option. I was able to successfully deploy the website using Azure services and connected it to a server with its own database.
One of the things I've been struggling with, however, is setting up Facebook authentication. I followed this guide: https://www.c-sharpcorner.com/article/authentication-using-facebook-in-asp-net-core-2-0/
and was able to successfully login with Facebook locally, but when I try to publish and go to the website with the new code in ConfigureServices function I get a HTTP 500 error.
My website is: vincecoreapp.azurewebsites.net
Here is the snippet that I inserted:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddAuthentication().AddFacebook(facebookOptions =>
{
facebookOptions.AppId = Configuration["Authentication:Facebook:AppId"];
facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
});
// Add application services.
services.AddTransient<IEmailSender, EmailSender>();
services.AddMvc();
}
Any advice would be extremely helpful, thank you!
My guess would be that you haven't added the published "something.azurewebsites.net" URL to the Valid OAuth Redirect Settings in your Facebook App Settings
namespace VinceCoreApp
{
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.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddAuthentication().AddFacebook(facebookOptions =>
{
facebookOptions.AppId = "680347028977338";
//Configuration["Authentication:Facebook:AppId"];
facebookOptions.AppSecret = "fc943b8782d7d5d83a4446709f2d903a";
//Configuration["Authentication:Facebook:AppSecret"];
});
// Add application services.
services.AddTransient<IEmailSender, EmailSender>();
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
This solved the problem