2

I'm a newbie looking for some help. I'm using netcoreapp2.2 for working in an already existing project and managed to put together a working Model from multiple questions and tutorials like so:

public class AdminViewModel : PageModel
{
    public string Username
    {
        get => GetCookie("username");
    }
    public string Password
    {
        get => GetCookie("password");
    }
    public void OnGet()
    {
    }

    private string GetCookie(string cookieName)
    {
        HttpContext context = HttpContext;
        HttpRequest request = context.Request;
        string result;
        if (request.Cookies.TryGetValue(cookieName, out result))
        {
            return result;
        }
        return "";
    }
}

With the View:

@model Regulator2App.Web.Views.Admin.AdminViewModel
@{
    string username = Model.Username;
    string password = Model.Password;
    bool isLoggedIn = username.Equals("admin") && password.Equals("admin");
}
@if (isLoggedIn)
{
    <div>"You're in!"</div>
}
else
{
    <button id="cookie">Create cookies</button>
}
<script src="~/js/admin.js"></script>

And the controller:

public class AdminController : Controller
{
    [HttpGet("/admin/")]
    public IActionResult AdminView()
    {
        return View(new AdminViewModel());
    }
}

My idea is adding a listener on the Create cookies button to add some cookies and then retrieve them via the model, the problem I'm facing is that my context is always null:

NullReferenceException: Object reference not set to an instance of an object.
AdminViewModel.GetCookie(string cookieName) in AdminView.cshtml.cs
HttpRequest request = context.Request;

How can I properly access the context to retrieve the cookies?

IvanHid
  • 669
  • 7
  • 25
  • 1
    As far as I am aware the HttpContext property should not be null. However, an alternative would be to inject an `IHttpContextAccessor`, I wouldn't suggest this until you have figured out the problem. – devtoka Jul 26 '20 at 06:33
  • 1
    Agreed, it looks fine. Can you share the exact exception stack trace? – marcusturewicz Jul 26 '20 at 07:17

1 Answers1

4

HttpContext is null because you are creating AdminViewModel instance manually but it should be created by the framework. The problem is that you are mixing razor pages with controllers while these are completely different things and should not be used together as I mentioned in my other answer.

Alexander
  • 9,104
  • 1
  • 17
  • 41
  • Thank you! I'm using razor pages only and simplified the code to look like this: @{ string username; Context.Request.Cookies.TryGetValue("username", out username); } – IvanHid Aug 03 '20 at 02:37