Fred
Fred

Reputation: 4076

How to avoid rendering Asp.net Core razor pages when redirecting?

I've got code at the start of my OnGet method which basically says just checks if a query string parameter exists and if not sets the redirect on the Response object and returns.

What I'm finding is that it still attempts to render the page, which ends up throwing a NullReferenceException.

I can obviously fix this by making sure the value in the viewbag isn't null, but I feel like the better solution is to have the razor page not render. I've done some googling and haven't found any information on it.

Is there a way to tell asp.net core 3.x not to render a razor page?

Upvotes: 4

Views: 930

Answers (1)

Fred
Fred

Reputation: 4076

Mike Brind's comment gave me what I needed to find the solution. You need to adjust the OnGet/Post methods to return an IActionResult and return a RedirectToPageResult object.

public IActionResult OnGet() {
    var queryParam = Request.Query["queryParam"].ToString();
    if(string.IsNullOrWhiteSpace(queryParam))
        return new RedirectToPageResult("OtherPageName");

    // do stuff
    return new PageResult();
}

Upvotes: 5

Related Questions