0

I am starting to learn ASP.NET MVC. Now I am trying to create an application that supports personal accounts without class Membership, class FormsAuthentication etc. I was surfing the programming forums to solve the problem below for nearly 4 hours, now I'm exhausted...

If the user doesn't check the "Remember" box in the login form, my app saves username to the current session:

HttpContext.Session.Set("authentication", Encoding.Unicode.GetBytes(username));

And when the user tries to open the personal account page, my app tries to get the saved value from session:

if (!HttpContext.Session.TryGetValue("authentication", out username)) {
    return RedirectToAction("Login", "Account");
}

It displays the value using function Controller.Content. But when I enter username "SNBS" and click "Login", it displays the following nonsense:

The personal account interface will be here. Your username: UwBOAEIAUwA=

Note: the rest of login/logout functionality works properly: when I try to open personal account page without authenticating, it redirects me to login page, etc.

I suppose the problem is caused by encodings, as HttpContext.Session.Set receives a byte array in parameter value. I tried changing Encoding.Unicode.GetBytes to Encoding.UTF8.GetBytes and to other encodings, but it just changed the nonsense displayed. I also tried using System.Convert — it gave the same result. Now I don't know what to try, as session usage includes not more than five lines of code and there is simply nothing that could work improperly...

SNBS
  • 671
  • 2
  • 22
  • 2
    Its base64 encoded. Convert.FromBase64String helps. – Ralf Nov 05 '22 at 15:18
  • **Note**. The `Convert` class sometimes gives some errors that are not easy to fix. I faced one of them (about unexpected padding characters, though there aren't any padding characters in the string I gave it). So I would replace it with `Encoding.UTF8` which works properly. – SNBS Nov 08 '22 at 08:58

0 Answers0