Remove ReturnUrl while using ASP.NET Identity

943 views Asked by At

I know this question is posted many times, but I am still overwhelmed.

I am using Identity in my ASP.NET MVC Project.

Note: My project is not completely an SPA but something in between, so I need the user to simply go to the "home page" if he/she is not logged-in.

But by using the "Authorize" attribute, there would always be a "ReturnUrl" appended as a query string.

According to what I read in the link below, there is no easy configuration for this matter:

Simple way to remove ReturnUrl - GitHub

And I couldn't find out where should I add the code mentioned in the above link, which is:

.AddCookie(options =>

So what I did as a workaround:

  1. According to the default behavior of ASP.NET Identity, if user is not logged-in, user will be redirected to an action.
  2. I changed the "login path" this way:
services.ConfigureApplicationCookie(options => 
   {options.LoginPath = new PathString("/notsignedin");
});

and then created its action, and what this action does is to redirect the user to the "home page" without the "ReturnUrl" query string. The code is as follows:

[Route("notsignedin")]
public IActionResult NotSignedIn()
{
   return RedirectToAction("Index");
}

Although it works, but I don't really like it because it redirects the user twice.

Since I'm a beginner I am not really aware of all the features available in ASP, so I appreciate any help.

1

There are 1 answers

0
Hamed Homaee On BEST ANSWER

I found the solution finally after several months.

Note, the question was created with .net5 but the answer is .net6, there is not much difference!

This is the code I should have added to change the "challenge" functionality:

builder.Services.ConfigureApplicationCookie(options =>
{
   options.Events.OnRedirectToLogin = opt =>
    {
        opt.HttpContext.Response.Redirect("/login");
        return Task.FromResult(0);
    };
});

The return Task.FromResult(0); part is added because a Task should have been returned.

Please tell me if there is a better approach.