Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UnknownSessionKeyException - errors for registered keys #322

Closed
whatsaaaa opened this issue Apr 12, 2023 · 5 comments
Closed

UnknownSessionKeyException - errors for registered keys #322

whatsaaaa opened this issue Apr 12, 2023 · 5 comments

Comments

@whatsaaaa
Copy link

Describe the bug

When trying to read Session from the .NET 7 application, I receive UnknownSessionKeyException. It provides a list of unknown session keys, but the issue is that it lists registered session keys.

To Reproduce

Here is the code for the Program.cs file of .NET 7 application:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSystemWebAdapters()
    .AddSessionSerializer(options =>
    {
        options.ThrowOnUnknownSessionKey = true;
    })
    .AddJsonSessionSerializer(options =>
    {
        options.KnownKeys.Add("SessionToken", typeof(Guid));
    })
    .AddRemoteAppClient(options =>
    {
        options.RemoteAppUrl = new(builder.Configuration["ProxyTo"]);
        options.ApiKey = "f2a03156-7d86-43cf-95f1-ecf2606be0aa";
    })
    .AddSessionClient();
​
builder.Services.AddHttpForwarder();// Add services to the container.
builder.Services.AddControllersWithViews();var app = builder.Build();if (!app.Environment.IsDevelopment())
{
    app.UseHsts();
}
​
app.UseHttpsRedirection();
app.UseStaticFiles();
​
app.UseRouting();
app.UseAuthorization();
app.UseSystemWebAdapters();
​
app.MapDefaultControllerRoute()
    .RequireSystemWebAdapterSession();
​
app.MapForwarder("/{**catch-all}", app.Configuration["ProxyTo"])
    .Add(static builder => ((RouteEndpointBuilder)builder).Order = int.MaxValue);
​
app.Run();

As you can see, I only added SessionToken as a known key. The same applies to the Global.asax code in the ASP.NET Framework app:

SystemWebAdapterConfiguration.AddSystemWebAdapters(this)
               .AddSessionSerializer(options =>
               {
                   options.ThrowOnUnknownSessionKey = false;
               })
               .AddJsonSessionSerializer(options =>
               {
                   options.KnownKeys.Add("SessionToken", typeof(Guid));
               })
               .AddRemoteAppServer(options =>
               {
                   options.ApiKey = "f2a03156-7d86-43cf-95f1-ecf2606be0aa";
               })
               .AddSessionServer();

When I run the application and attempt to hit the endpoint in which I read the Session, I receive the following error:

image

What confuses me is why the error lists SessionToken, amongst other unregistered session keys.

I tried turning the ThrowOnUnknownSessionKey option off, and then I didn't receive the exception from the above image, but there are no values in Session.

Should I include something in my configuration, or must I register all the keys for the session to work correctly?

Further technical details

ASP.NET Framework Application:

  • Technologies and versions used (i.e., MVC/WebForms/etc.): MVC
  • .NET Framework Version: .NET Framework 4.8
  • IIS Version: IIS 10 Express
  • Windows Version: Windows 10

ASP.NET Core Application:

  • Targeted .NET version: .NET 7
  • .NET SDK version: .NET 7
@twsouthwick
Copy link
Member

Are you sure it's a Guid? In order to serialize, it must match the name as well as the type registered?

Can you show an example of where you set the session value for SessionToken?

@twsouthwick
Copy link
Member

I've added a PR to give better warnings for if the type is not correct (not sure if that is the issue here, but we don't have good diagnostics on that)

@whatsaaaa
Copy link
Author

Thanks for the PR. It will be super helpful to prevent errors like this.

I doubled checked, and I got the type wrong. SessionToken is converted to a string before it is written to the Session. The code for that looks something like this:

HttpContext.Session["SessionToken"] = Guid.NewGuid().ToString();

I changed the code for registering the Session keys: and used typeof(string); With that change, the above error is gone, but now I receive a different kind of error:
image

I will keep looking for what could be wrong with the configuration.

And here is the log:

      Unable to load remote session state for session w2jizel50xv0s5svo5bxcj2r
      [System.Net](http://system.net/).Http.HttpRequestException: Response status code does not indicate success: 500 (Internal Server Error).
         at [System.Net](http://system.net/).Http.HttpResponseMessage.EnsureSuccessStatusCode()
         at Microsoft.AspNetCore.SystemWebAdapters.SessionState.RemoteSession.RemoteAppSessionStateManager.GetSessionDataAsync(String sessionId, Boolean readOnly, HttpContext callingContext, CancellationToken token)
         at Microsoft.AspNetCore.SystemWebAdapters.SessionState.RemoteSession.RemoteAppSessionStateManager.CreateAsync(HttpContext context, SessionAttribute metadata)
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
      An unhandled exception has occurred while executing the request.
      [System.Net](http://system.net/).Http.HttpRequestException: Response status code does not indicate success: 500 (Internal Server Error).
         at [System.Net](http://system.net/).Http.HttpResponseMessage.EnsureSuccessStatusCode()
         at Microsoft.AspNetCore.SystemWebAdapters.SessionState.RemoteSession.RemoteAppSessionStateManager.GetSessionDataAsync(String sessionId, Boolean readOnly, HttpContext callingContext, CancellationToken token)
         at Microsoft.AspNetCore.SystemWebAdapters.SessionState.RemoteSession.RemoteAppSessionStateManager.CreateAsync(HttpContext context, SessionAttribute metadata)
         at Microsoft.AspNetCore.SystemWebAdapters.SessionMiddleware.ManageStateAsync(HttpContext context, SessionAttribute metadata)
         at Microsoft.AspNetCore.SystemWebAdapters.PreBufferRequestStreamMiddleware.InvokeAsync(HttpContext context)
         at Microsoft.Extensions.DependencyInjection.RegisterAdapterFeaturesMiddleware.InvokeAsync(HttpContext context)
         at Microsoft.Extensions.DependencyInjection.RegisterAdapterFeaturesMiddleware.InvokeAsync(HttpContext context)
         at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
         at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
         at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)```

@whatsaaaa
Copy link
Author

I figured out what was wrong with my setup. One of the shared class libraries was missing a Microsoft.AspNetCore.SystemWebAdapters package.

Right now, everything is working as expected.

I overlooked that installing the package to the class libraries is required.

Thanks a lot for the help and this fantastic package, it is a new life for our old and rusty application 😄

@twsouthwick
Copy link
Member

Great! Sounds like the PR to have better logging for type issues will help here. I'll go ahead and close this issue. Please raise a new one if you have more issues

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants