I have an ASP.Net vNext project that uses Session. But I am getting this error while trying to get/set values in the session.
An exception of type 'System.InvalidOperationException' occurred in Microsoft.AspNet.Http.Core.dll but was not handled in user code
Additional information: Session has not been configured for this application or request.
Here's my controller method:
[AllowAnonymous]
[HttpGet("/admin")]
public IActionResult Index()
{
if (Context.Session.GetString("UserName") == null) // error thrown here
{
return RedirectToAction("Login");
}
return View();
}
I have added the KVM package "Microsoft.AspNet.Session": "1.0.0-beta3" in my project.json file as well and have configured my application to use session via my Startup.cs like so:
public void ConfigureServices(IServiceCollection services)
{
// code removed for brevity
services.AddCachingServices();
services.AddSessionServices();
}
public void Configure(IApplicationBuilder app)
{
app.UseMvc();
app.UseInMemorySession(configure: s => s.IdleTimeout = TimeSpan.FromMinutes(30));
}
I have looked at the vNext documentation on Github but it does not provide much information about ASP.Net sessions. What am I doing wrong?
So I figured this out. The fix was quite simple actually. Since ASP.Net adds the middlewares sequentially into the request pipeline, all I needed to do was use the session middleware before using MVC. More info here: https://stackoverflow.com/a/29569746/832546
Fixed code:
public void Configure(IApplicationBuilder app)
{
app.UseInMemorySession(configure: s => s.IdleTimeout = TimeSpan.FromMinutes(30));
app.UseMvc();
}
Thanks to #acrhistof the link helped.
So if you are using RC1:
add this these dependencies in project.json:
"Microsoft.AspNet.Session": "1.0.0-rc1-final",
"Microsoft.Extensions.Caching.Memory": "1.0.0",
in Startup.cs file:
public void ConfigureServices(IServiceCollection services)
{
services.AddCaching();
services.AddSession();
services.AddMvc();
}
and
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseSession(); //outside of dev if (env.IsDevelopment())
....
}
It seems like things changed once again and the well-known ASP.NET session has to be configured differently in the rc1. (no UseInMemorySession() or other AppBuilder methods are related to Session, now it is added as a service).
In general Session has to be installed, configured, and then used. All these steps are quite new and somewhat unusual. Moreover, it depends on Cache:
Session is built on top of IDistributedCache, so you must configure
this as well, otherwise you will receive an error.
The quotation above is from ASP.NET 5 docs. All you need to do is described here: https://docs.asp.net/en/latest/fundamentals/app-state.html#installing-and-configuring-session.
Related
In my aspnetcore app (v2.1) I need to configure a read-only database (entityframework core + SQLite) which is in ~/wwwroot/App_Data/quranx.db
I need to call this code in Startup.ConfigureServices
services.AddDbContext<QuranXDataContext>(options => options
.UseSqlite($"Data Source={databasePath}")
.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)
);
But at that point I cannot find a way to get the path to wwwroot. To get that path I need IHostingEnvironment, but I am unable to get a reference to that until Startup.Configure is called, and that is after Startup.ConfigureServices has finished.
How is this done?
It's easy enough to access IHostingEnvironment in ConfigureServices (I've explained how below) but before you read the specifics, take a look at Chris Pratt's warning in the comments about how storing a database in wwwroot is a very bad idea.
You can take a constructor parameter of type IHostingEnviroment in your Startup class and capture that as a field, which you can then use in ConfigureServices:
public class Startup
{
private readonly IHostingEnvironment _env;
public Startup(IHostingEnvironment env)
{
_env = env;
}
public void ConfigureServices(IServiceCollection services)
{
// Use _env.WebRootPath here.
}
// ...
}
For ASP.NET Core 3.0+, use IWebHostEnvironment instead of IHostingEnvironment.
Path.GetFullPath("wwwroot");
I've got an older asp.net core identity database, and I want to map a new project (a web api) to it.
Just for the test, I copied the Models folder, and the ApplicationUser file from the previous project (ApplicationUser simply inherits from IdentityUser, no changes whatsoever) - doing DB first seems to be a bad idea.
I'm registering Identity in ConfigureServices (but I'm not adding it to the pipeline since my only intention is to use the UserStore)
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
My expectation is that now
UserManager<ApplicationUser>
...should be automatically injected into constructors.
However, when adding the following code to a controller
private UserManager _userManager;
public UserController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
... every call to the api ends with an exception:
HttpRequestException: Response status code does not indicate success: 500 (Internal Server Error).
Removing the "injection" code results in smoothly running web api that can accept requests.
It's hard to debug as this occurs before any of my code is reached. Any idea why this is occurring?
P.S. After enabling all exceptions from the Exception Settings window I got this one:
Exception thrown: 'System.InvalidOperationException' in
Microsoft.Extensions.DependencyInjection.dll
Additional information: Unable to resolve service for type
'Namespace.Data.ApplicationDbContext' while attempting to activate
'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`4[Namespace.Models.
ApplicationUser,Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole,Namespace.Data.ApplicationDbContext,System.String]'.
Do you have the app.UseIdentity(); call in the Configure method:
public void Configure(IApplicationBuilder app,
IHostingEnvironment env, ILoggerFactory loggerFactory)
{
/*...*/
app.UseIdentity();
/*...*/
}
EDIT
Do you also have this line before the services.AddIdentity<ApplicationUser, IdentityRole>() line?
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
This should work OK. Also please check if ApplicationDbContext inherits from IdentityDbContext.
DI container is unable to resolve a dependency. Add it to the services collection
services.AddTransient<UserManager<ApplicationUser>>();
services.AddTransient<ApplicationDbContext>();
You should also familiarize yourself with the official documentation
public void ConfigureServices(IServiceCollection services){
...
var identityBuilder = services.AddIdentityCore<ApplicationUser>(user =>
{
// configure identity options
user.Password.RequireDigit = true;
user.Password.RequireLowercase = false;
user.Password.RequireUppercase = false;
user.Password.RequireNonAlphanumeric = false;
user.Password.RequiredLength = 6;
});
identityBuilder = new IdentityBuilder(identityBuilder.UserType, typeof(IdentityRole), identityBuilder.Services);
identityBuilder.AddEntityFrameworkStores<DbContext>().AddDefaultTokenProviders();
...
}
I have a working webpage (front-end strictly) and I was curious of I could add a WebApi without leaving VS Code. So I created a directory called webapi in the root of my project and added a file demo.cs containing the following.
using Microsoft.AspNetCore.Mvc;
namespace WebApi
{
[Route("api/[controller]")]
public class Demo : Controller
{
[HttpGet] public string Ping() { return "yo!"; }
}
}
After some googlearching for references, I made sure that my project.json contains the following.
"Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
"Microsoft.AspNetCore.StaticFiles": "1.0.0",
"Microsoft.AspNetCore.Mvc.Core": "1.0.1",
I also edited the configuration methods like this.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore();
services.AddDirectoryBrowser();
}
public void Configure(IApplicationBuilder app,
IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
app.UseMvc();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseFileServer(true);
app.UseMvcWithDefaultRoute();
}
Now, as I execute the project with dotnet run, I get no errors, the page functions but I can't seem to access the text I meant to expose. The extra problem's that I'm not sure if I've got the WebApi running but using the wrong URL (I went localhost:port with /api/donkey) or if it's not running at all.
How can I verify that it's up? What would be the address? Is there something else I'm missing in the setup?
The guides tell partially different things, which I guess depends on the rapid evolution of NET.Core. Not sure how to proceed.
Using documentation from
Routing to Controller Actions
To make attribute routing less repetitive, route attributes on the
controller are combined with route attributes on the individual
actions. Any route templates defined on the controller are prepended
to route templates on the actions. Placing a route attribute on the
controller makes all actions in the controller use attribute routing.
using Microsoft.AspNetCore.Mvc;
namespace WebApi {
[Route("api/[controller]")]
public class Demo : Controller {
[HttpGet] // Matches 'GET /api/Demo'
public string Ping() {
return "yo!";
}
}
}
the start up should have this in the configure services
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) {
// Add framework services.
services.AddMvc();
//...other code
}
I'm starting a new project in VS 2015.
File -> New -> Project -> ASP.NET Web Application -> ASP.NET 5 Templates -> Web API
A project is initialized. I would assume that if I run the project with IIS Express a service would be available.
It runs through the startup methods.
public class Startup
{
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
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, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseIISPlatformHandler();
app.UseStaticFiles();
app.UseMvc();
}
// Entry point for the application.
public static void Main(string[] args) =>
WebApplication.Run<Startup>(args);
}
}
But then it crashes. I don't know how to implement global error handling.
I looked at this example.
But when I try to use System.Net.Http or System.Web.Http.ExceptionHandling they can't be found.
I also noticed that through intellisense it says Core 5.0 is no available.
Here is my project.json as requested.
{
"version":"1.0.0-*",
"compilationOptions":{
"emitEntryPoint":true
},
"dependencies":{
"Microsoft.AspNet.IISPlatformHandler":"1.0.0-rc1-final",
"Microsoft.AspNet.Mvc":"6.0.0-rc1-final",
"Microsoft.AspNet.Server.Kestrel":"1.0.0-rc1-final",
"Microsoft.AspNet.StaticFiles":"1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.FileProviderExtensions":"1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Json":"1.0.0-rc1-final",
"Microsoft.Extensions.Logging":"1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Console":"1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Debug":"1.0.0-rc1-final"
},
"commands":{
"web":"Microsoft.AspNet.Server.Kestrel"
},
"frameworks":{
"dnx451":{
"frameworkAssemblies":{
"System.Web":"4.0.0.0"
}
},
"dnxcore50":{
}
},
"exclude":[
"wwwroot",
"node_modules"
],
"publishExclude":[
"**.user",
"**.vspscc"
]
}
Try to open Visual Studio Administrator Mode
I guess it depends on what is crashing - it's not clear from your description what crashes, when it crashes and how it crashes.
You can use UseExceptionHandler and UseDeveloperExceptionPage extension methods to configure an error handling page. This article describes it in more details.
If the exception happens during startup you may need to use UseCaptureStartupErrors extension method (it was recently renamed to CaptureStartupErrors).
Also, you already have logging enabled - the logs may also have some useful information. If you can't see logs because you log to the console consider logging to a file.
If this is IIS/IISExpress crashing check event log.
What is your runtime version ?
Maybe you can try scaffolding your application with the AspNet Yeoman generator and compare the files.
Personally I prefer to use the scaffolder as it is often up to date.
Hope this helps !
Alright, so recently I've been having a lot of trouble using the new Microsoft.AspNet.Session middleware for ASP.NET vNext (MVC 6). The error I'm getting,
Unable to resolve service for type
'Microsoft.Framework.OptionsModel.ConfigureOptions[Microsoft.AspNet.Session.SessionOptions]
while attempting to activate
'Microsoft.AspNet.Session.SessionMiddleware'
occurs on all pages regardless of session use. The DNVM version I'm using is Beta5 x86 and all the packages in the project are Beta5 as well. The project itself is an attempt at porting an ASP.NET MVC 5 project to MVC 6 without much luck. Below are links to resources that may be important:
Project.json: http://tinyurl.com/project-json
Startup.cs: http://tinyurl.com/startup-cs
It seems to be a problem with my configuration but I'm not sure what to do about it... Pls send help Dx
Unable to resolve service for type 'Microsoft.AspNetCore.Session.ISessionStore' while attempting to activate 'Microsoft.AspNetCore.Session.SessionMiddleware'
If you get this error message in ASP.NET Core, you need to configure the session services in Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddSessionStateTempDataProvider();
services.AddSession();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSession();
app.UseMvcWithDefaultRoute();
}
This code helps you...
In Startup.cs file
public void ConfigureServices(IServiceCollection services)
{
....
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);//We set Time here
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSession();
app.UseMvc();
}
Thanks!!!
you can add session middleware into configure method in the startup.
public void ConfigureServices(IServiceCollection services) {
services.AddSession();
services.AddMvc();
}
Step 1: Install "Microsoft.AspNetCore.Session" this package.
Step 2: Add these functions in configure services function in the startup file.
(1). services.AddSession();
(2). services.AddDistributedMemoryCache();
Step 3: Add "app.UseSession()" use session function in Configure function in the startup file.
ASP.NET CORE 6.0
In program.cs file add this
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(1800);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
Then
app.UseSession();
For more Read official doc
For ASP.NET 7 there is no longer a Startup.cs file, as it is merged with the Program.cs file. Instead add
builder.Services.AddSession();
builder.Services.AddDistributedMemoryCache();
above
var app = builder.Build();
Then you can add
app.UseSession();
I am using .net core 5 . I was getting the same issue
this is how i solved it
public void ConfigureServices(IServiceCollection services)
{
services.AddSession();
services.AddMvc();
}
I have added these and I have also added these ,
I added it to the startup.cs class
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
}
My problem is solved, I hope yours is solved too.
app.usesession() in the program.cs file; I deleted your method and it was fixed