Kes*_*lme 27 asp.net-mvc asp.net-web-api
我是asp.net的新手我最近遇到过这个例外:
System.InvalidOperationException
例外的细节说:
尚未为此应用程序或请求配置会话.
以下是它发生的代码段:
[HttpPost]
public object Post([FromBody]loginCredentials value)
{
if (value.username.Equals("Admin")
&&
value.password.Equals("admin"))
{
HttpContext.Session.Set("userLogin", System.Text.UTF8Encoding.UTF8.GetBytes(value.username)); //This the line that throws the exception.
return new
{
account = new
{
email = value.username
}
};
}
throw new UnauthorizedAccessException("invalid credentials");
}
Run Code Online (Sandbox Code Playgroud)
我不知道为什么会发生这种错误或者这个错误究竟意味着什么.有人可以解释可能导致这种情况的原因吗?
Aus*_*orn 59
在您的Startup.cs中,您可能需要调用
app.UseMvc之前的app.UseSession
app.UseSession();
app.UseMvc(); Run Code Online (Sandbox Code Playgroud)
par*_*ox1 30
转到您的Program.cs第一个(在那里添加代码)
我将其插入到构建器的最后部分:
builder.Services.AddSession();
Run Code Online (Sandbox Code Playgroud)
我在之后添加了这个app.UseAuthorization();
app.UseSession();
Run Code Online (Sandbox Code Playgroud)
注意:我不知道这是否真的是放置代码的“正确行”,但这对我有用。(我还是 ASP.NET 的初学者)
Gio*_*sos 16
我在 .NET Core 3.0 Razor Pages 应用程序中遇到了完全相同的错误。因为,我没有使用app.UseMvc()建议的答案对我不起作用。
因此,对于在 .NET Core 3.0 中遇到相同问题的任何人,以下是我在内部Configure为使其正常工作所做的工作:
app.UseSession(); // use this before .UseEndpoints
app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); });
Run Code Online (Sandbox Code Playgroud)
Following code worked out for me:
Configure Services :
public void ConfigureServices(IServiceCollection services)
{
//In-Memory
services.AddDistributedMemoryCache();
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(1);
});
// Add framework services.
services.AddMvc();
}
Configure the HTTP Request Pipeline:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
Run Code Online (Sandbox Code Playgroud)
对于.net核心5
应在startup.cs中添加以下几行
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(10);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
Run Code Online (Sandbox Code Playgroud)
app.UseSession();应该在之前添加
app.UseAuthentication();
app.UseAuthorization();
Run Code Online (Sandbox Code Playgroud)
下面的代码可用于设置值和读取值
this.httpContext.Session.SetString(SessionKeyClientId, clientID);
clientID = this.httpContext.Session.GetString(SessionKeyClientId);
Run Code Online (Sandbox Code Playgroud)
Deb*_*aha -5
HttpContext.Session.Add("name", "value");
Run Code Online (Sandbox Code Playgroud)
或者
HttpContext.Session["username"]="Value";
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17100 次 |
| 最近记录: |