Reputation: 427
I'm checking user is authorized already or not in global.asax if true then redirect to some route
if (false)
{
HttpContext.Current.Response.RedirectToRoute("Login");
}
It throws exeption :
Response is not available in this context
Upvotes: 0
Views: 5048
Reputation: 8197
As far as I know, ASP.NET creates HttpContext
object together with HttpRequest
and HttpResponse
objects. It happens before creation of the HttpApplication
instance.
So it seems that HttpContext.Current
just doesn't work at this stage.
Inside application event's handlers you can get the context throw the sender
:
private void OnAuthorizeRequest(object sender, EventArgs e)
{
var application = (HttpApplication)sender;
var context = (HttpContext)application.Context;
}
(AuthorizeRequest
is a right place to redirect anonymous users, cause previous AuthenticateRequest
has authenticated or hasn't authenticated the user already.)
See details here.
It's important: the neighbor answer is absolutely correct, and you should use web.config
to make this thing. My answer about "how it works", and "how it could be done".
Upvotes: 0
Reputation: 8359
I think it would be a better solution to make use of the authentication tag in the web.config
.
// or loginUrl="~/Account/LogOn" for example in an MVC application
<authentication mode="Windows">
<forms
name=".ASPXAUTH"
loginUrl="login.aspx"
defaultUrl="default.aspx"
protection="All"
timeout="30"
path="/"
requireSSL="false"
slidingExpiration="true"
cookieless="UseDeviceProfile" domain=""
enableCrossAppRedirects="false">
<credentials passwordFormat="SHA1" />
</forms>
<passport redirectUrl="internal" />
</authentication>
You can define a loginUrl where the user will be redirected in case the user tries to access a ressource which requires authentication.
Update
According to your given comment I think you may be looking for an authorization based routing. There is already an answer for that in this SO Question MVC role-based routing.
Upvotes: 3