我是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)
我不知道为什么会发生这种错误或者这个错误究竟意味着什么.有人可以解释可能导致这种情况的原因吗?
我试图在我的ASP.NET Core 1.0(vNEXT)项目中使用Session.这就是我的代码的样子.
public class Startup
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
//-- Enabled MVC Pattern
services.AddMvc();
//-- Enable Session handling
services.AddCachingServices();
services.AddSessionServices();
}
public void Configure(IApplicationBuilder app)
{
//-- User MVC
app.UseMvc();
//-- Use Session
app.UseSession();
app.UseInMemorySession();
}
}
Run Code Online (Sandbox Code Playgroud)
但现在我被卡住了.我不知道如何在我的控制器或页面中设置或从会话中获取数据.我试过了.Context.Session.但它没有实例化,因此当我尝试访问该属性时会抛出一个invalidexception.
任何拥有如何使其工作的代码示例的人.
提前致谢.
编辑:
这是screendump我的控制器中base.context.Session的样子.

我没有SetString()和GetString(),只有Set()和TryGet()......方法......
这就是我的project.json文件的样子.
"version": "1.0.0-*",
"dependencies": {
"Microsoft.AspNet.Server.IIS": "1.0.0-beta3",
"Microsoft.AspNet.Mvc": "6.0.0-beta3",
"Microsoft.AspNet.Session": "1.0.0-beta3"
},
Run Code Online (Sandbox Code Playgroud)