IvanHid
IvanHid

Reputation: 709

Why is my HttpContext null on a Razor Page View Model?

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?

Upvotes: 2

Views: 2270

Answers (1)

Alexander
Alexander

Reputation: 9632

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.

Upvotes: 4

Related Questions