asp.net-mvc 尚未为此应用程序配置会话或请求错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50619634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:55:47  来源:igfitidea点击:

Session has not been configured for this application or request error

asp.net-mvcasp.net-web-api

提问by Keselme

I am very new to asp.net I recently I came across this exception:

我对 asp.net 很陌生,最近我遇到了这个异常:

System.InvalidOperationException

System.InvalidOperationException

The details of the exception says:

异常的详细信息说:

Session has not been configured for this application or request.

尚未为此应用程序或请求配置会话。

Here is the code snippet where it happens:

这是它发生的代码片段:

[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");
        }

I have no idea why it's happening or what does this error actually mean. Can someone please explain what might be causing this?

我不知道为什么会发生这种错误,也不知道这个错误究竟意味着什么。有人可以解释一下可能导致这种情况的原因吗?

回答by Austin Born

In your Startup.cs you might need to call

在您的 Startup.cs 中,您可能需要调用

app.UseSession before app.UseMvc

app.UseSession 在 app.UseMvc 之前

app.UseSession();  
app.UseMvc();  

For this to work, you will also need to make sure the Microsoft.AspNetCore.Sessionnuget package is installed.

为此,您还需要确保安装了Microsoft.AspNetCore.Sessionnuget 包。

Update

更新

You dont not need to use app.UseMvc(); in .NET Core 3.0 or higher

你不需要使用 app.UseMvc(); 在 .NET Core 3.0 或更高版本中

回答by Uttam

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:

配置 HTTP 请求管道:

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?}");
     });
 }

回答by Giorgos Betsos

I was getting the exact same error in my .NET Core 3.0 Razor Pages application. Since, I'm not using app.UseMvc()the proposed answer could not work for me.

我在 .NET Core 3.0 Razor Pages 应用程序中遇到了完全相同的错误。因为,我没有使用app.UseMvc()建议的答案对我不起作用。

So, for anyone landing here having the same problem in .NET Core 3.0, here's what I did inside Configureto get it to work:

因此,对于在 .NET Core 3.0 中遇到相同问题的任何人,以下是我在内部Configure为使其正常工作所做的工作:

app.UseSession(); // use this before .UseEndpoints
app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); });

回答by Debashish Saha

HttpContext.Session.Add("name", "value");

OR

或者

HttpContext.Session["username"]="Value";