I was recently using a Bootstrap template that had static navigation and menu items. Since we were using this in a _Layout Razor View and using the @RenderBody section for all of our Views, when the Forms Authentication Cookie would time out or expire, we would end up with the Login page inside of our existing _Layout page rather than completely replacing the entire _Layout view!
Well, fortunately, this was fixed through some JavaScript on our _Login view:
Well, fortunately, this was fixed through some JavaScript on our _Login view:
<script type="text/javascript">
if (window.top.location.pathname.indexOf("/Account/Login")<0)
{
window.top.location.href = window.top.location.origin + "/Account/Login";
}
</script>
If you find it tedious to try and get the exact Url path in JavaScript, you can get the Paths in C# using methods such as the following:
public static string GetLocalPath(HttpContext context)
{
string baseUrl = string.Empty;
baseUrl = string.Format("{0}://{1}{2}", context.Request.Url.Scheme, context.Request.Url.Authority, context.Request.Url.LocalPath);
return baseUrl;
}
public static string GetFQDN(HttpContext context)
{
string baseUrl = string.Empty;
baseUrl = context.Request.Url.AbsolutePath;
return baseUrl;
}
Then you can assign these values in JavaScript using the following code:
var loginPath = "@UrlHelpers.GetLocalPath(HttpContext.Current)";
var currentPath = "@UrlHelpers.GetFQDN(HttpContext.Current)";
Then your JavaScript just becomes the following:
<script type="text/javascript">
if (window.top.location.pathname.indexOf("/Account/Login")<0)
{
window.top.location.href = loginPath;
}
</script>
That is all there is to it!!
No comments:
Post a Comment