I have a problem regarding those tutorials :
https://msdn.microsoft.com/en-us/library/xdt4thhy%28v=vs.140%29.aspx
I ve create my own site with those tips, so on my HTML file, I ve of course insert inside the form :
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
I've create a Logon.aspx page in order to put the login form, and by click, the button call a javascript function login():
<script type="text/javascript">
function login() {
var user = $('#username').val();
var password = $('#password').val();
PageMethods.login_GO(user, password, ok, ko);
function ok(result) {
alert(result);
}
function ko(result) {
alert('Cannot process your request at the moment, please try later.');
}
}
</script>
then the javascript function call a behind code method (inside the Logon.aspx.cs file)
[WebMethod]
public string login_GO(string user, string password)
{
if (user == "cool" && password == "whau")
{
FormsAuthentication.RedirectFromLoginPage(user, true);
return "done";
}
else
{
return "KO";
}
}
The only answer I have is an alert messagebox from the browser:
Cannot process your request at the moment, please try later.
Why do you think this method doesnt work ?
I mean normally I dont need anything else isnt ?
Thanks in advance !
EDIT:
Before I started to debug the code, I decide to disable the Authentication feature in the Web.config configuration (I only put a comment on all those lines below) :
<authentication mode="Forms">
<forms loginUrl="Logon.aspx" name=".ASPXFORMSAUTH" defaultUrl="PlazaMonitor.aspx" >
</forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>-->
So now, I can call the login_GO method on the behind code (Logon.aspx.cs).
Every works fine, but not the Authentication (because I disabled it)
The goal of all of this, is to authenticate an user using a behind code method, so if I need to be Authenticated before I use the Authentication Method I m going to be crazy ^^ !
EDIT :
I just understand, EVERY ressource should be disabled until you are AUTHENTICATE, so even the WebMethod used to be authenticate is disabled !
Do you know where (in Web.config certainely) we could change/allow the good ressources we need ?
Thanks in advance for your help ;) !
Related
During website development in asp.net, there's an issue of back button after logout.
I have tried writing the following code, it still doesn't work:
Session.Abandon();
Session.Clear();
Session.Contents.RemoveAll();
FormsAuthentication.SignOut();
Roles.DeleteCookie();
FormsAuthentication.RedirectToLoginPage();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetNoStore();
Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
Response.Redirect("~/Login.aspx");
On pressing the logout button, I don't want to get back to the previous URL. Help me out pls
Here is a working solution for the browser back button issue.
Step 1: Add the following hidden field on your page:
<input id="reloadValue" type="hidden" name="reloadValue" value="" />
Step 2: Add the following code on your page. Note that you should keep any existing document.ready() as it is and also add this one.
<script type="text/javascript">
$(document).ready(function () {
var d = new Date();
d = d.getTime();
if ($('#reloadValue').val().length == 0)
{
$('#reloadValue').val(d);
$('body').show();
}
else
{
$('#reloadValue').val('');
location.reload();
}
});
</script>
Note: This can be done in the master page as well, thus working for all pages.
Session.Abandon();
Response.Redirect("~/Home.aspx");
after session abandon redirect to any page with session on it
and session should be like this
if (Session["anyhthing"] == null)
{
Response.Redirect("~/Login.aspx");
}
I am building a web application using .net MVC 4.
I have ajax form to edit data.
If the user is idle for 15 mins it will expire the session of the user. When that happens if user click edit button it loads the login page inside the partial content hence now the current session expires.
Edit Link - cshtml code
#Ajax.ActionLink("Edit", MVC.Admin.Material.ActionNames.TagEditorPanel, MVC.Admin.Material.Name, new { isView = "false", id = Model.ID.ToString() }, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "materialTagBox", InsertionMode = InsertionMode.Replace }, new { #class = "editlinks" })
Controller/Action Code
[Authorize]
public virtual ActionResult TagEditorPanel(bool isView, int id)
{
//do something
return PartialView(MVC.Admin.Material.Views._tag, response);
}
Web.config
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
I understand why it is happening. I don't know how to resolve it. I want to prevent it and I want to redirect user to login page directly. How can I achieve this?
Thanks inadvance..!!!
Maybe a hacky answer, but you can change the redirect location in forms authentication to a page that sets the window location to the login page with javascript.
Web Config
<authentication mode="Forms">
<forms loginUrl="~/Account/RedirectToLogin" timeout="2880" />
</authentication>
Account Controller
public ActionResult RedirectToLogin()
{
return PartialView("_RedirectToLogin");
}
_RedirectToLogin View
<script>
window.location = '#Url.Action("Login", "Account")';
</script>
The issue is your call is intercepted by [Authorize] and sends the login page even before your action method code is called. One way to sort this out is to create a custom action filter to check the timeout and do a hard redirect to login page. Following post has a good write up which may help you in creating and registering the filter
http://www.codeblockdrive.com/2012/12/mvc-custom-filters-session-timeout.html
Best of luck
You may want to check the answer to this (similar) question.
ASP.NET MVC Partial view ajax post?
Basically it says that you should avoid making ajax calls to functions that may redirect because of this and other problems.
You can avoid the problem that you are having by authorizing / checking the expiration manually in your function, and then returning redirect information that can be applied to the whole page.
I have used this approach, and it works well.
Inspired by kramwens answer, one could avoid making an extra RedirectToLogin view (and controller action) and just put the following in you original Login view:
<script>
if (window.location != '#string.Format("{0}://{1}{2}",Request.Url.Scheme, Request.Url.Authority,Url.Content("~/Account/Login"))')
window.location = '#Url.Action("Login", "Account")';
</script>
This tests the current window.location and if it is not as expected, it sets it as expected.
I know, my js is a bit hacky and crappy, but it does the work :)
I Have simple way find for partial view session expired.
Simple One Action created then this view java script windows.load() call then url will be pass to this login page.
//in Controller one Action Created.
<script type="text/javascript">
window.location = '#Url.Action("Login", "LogIn")';
</script>
Public ActionResult SessionExpire()
{
return View();
}
//Redirect to login from partail view after session is null:
return Redirect("~/OrderPlace/Sessionview");
My solution is to use some c# code whenever possible. I can get the controller and view name, check to see of they are what they should be, and if not redirect to the proper.
var controllerName = ViewContext.RouteData.GetRequiredString("controller");
var actionName = ViewContext.RouteData.GetRequiredString("action");
I then use the following to go to the proper URL:
if (controllerName != "members" && actionName != "logon")
{
#{ Response.Redirect("~/Members/Logon");}
}
I have created an asp.net mvc razor application, in which I load a partial view in a div, which can be accessed after login.
<% using (Ajax.BeginForm("Showproducts", "Home", new AjaxOptions {
UpdateTargetId = "resdiv", OnBegin = "fstart()", OnSuccess = "fend()"
}, new { id = "_myform" }))
{ %>
.....
<% } %>
When a user leaves their computer for a long time (which makes the session time out automatically) and then clicks the submit button, the resdiv is filled with the full site with the login panel. I want to show the full site with login panel NOT in the resdiv. Is there any way to avoid this behavior?
Is there any way to avoid this behavior?
Yes, there is a way. I would recommend you reading the following blog post in which Phil Haack illustrates a very nice technique allowing you to override the Forms Authentication Module for AJAX requests and be able to send a 401 status code instead of redirecting to the login page.
Then on the client side you could use a global AJAX handler where you could test the status code and if it is 401 redirect to the logon page.
For example once you have installed the AspNetHaack NuGet you could add the following global error handler to your view:
<script type="text/javascript">
$(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
if (jqXHR.status == 401) {
// not authenticated => redirect to login page:
window.location.href = '#FormsAuthentication.LoginUrl';
}
});
</script>
I am developing application using Ajax and jsp.
My index.jsp page has HTML code for Login and some Ajax code in javascript. Ajax will call my another CheckLogin.jsp page
CheckLogin.jsp page checks on server for valid username and password. It returns "success" if it's valid otherwise will return message stating "username or password is not valid."
Now, when username and passwrod is valid, instead of success, I want to redirect the page to "Home.jsp" what should I do?
I am new to jsp. I appreciate your help on this.
JSP code gets run once on the server before it goes to the client, so JSP/JSTL cannot do a redirect following the success or otherwise of an AJAX call (without a full page refresh - which obviates the use of AJAX). You should to do the redirect with Javascript:
if (success) {
var successUrl = "Home.jsp"; // might be a good idea to return this URL in the successful AJAX call
window.location.href = successUrl;
}
On successful AJAX call/validation, the browser window will reload with the new URL (effectively a redirect).
Since I don't see your code, you can integrate this somewhere inside your validation :
<%
pageContext.forward("logged.jsp");
%>
function Edit() {
var allVals = $('#NEWFORMCampaignID').val();
if (allVals > 0) {
window.location = '/SMS/PrepareSMS?id='+allVals;
}
else
alert("Invalid campaign to Edit")
}
In order to redirect using Button click and pass some parameters, you can call the Controller Path(#RequestMapping(value="/SMS/PrepareSMS")) and then handle it there..
How can I redirect the viewer to a URL?
I noticed that someone asked How to redirect to another webpage in JavaScript/jQuery?, but I'm not exactly sure where this should go.
I have tried in the controller with:
window.location.replace("http://192.168.1.109/MWT/Taglist/ShowMap" + LastId);
and in the view with:
<% if (BreakCount >= 8) {
var url = "http://192.168.1.109/MWT/Taglist/ShowMap" + LastId;
window.location.replace(url);
} %>
Neither of these work. In both places places window has a red squiggly line underneath it and when I hover over it the message says "The name 'window' does not exist in the current context."
Any help would be greatly appreciated!
=D
Your question is tagged MVC 3, so I'll give you the answer for that in spite of the JavaScript example you listed. In your controller class use this code:
public ActionResult MyAction()
{
// Use this for an action
return RedirectToAction("ActionName");
// Use this for a URL
return Redirect("http://192.168.1.109/MWT/Taglist/ShowMap" + LastId);
}
This is occuring on the server, meaning that the client browser recieves a redirect response for which the browser will likely submit an additional request. If you return a page with JavaScript it will have to load a page, run the JavaScript (presuming it is enable on the client's browser), the load the next page. Among other problems, using JavaScript means that if the user presses the back button they will be repeatedly redirected again back to the page they are currently on.
Inside your controller call return RedirectToAction().
public ActionResult MyAction() {
return RedirectToAction("Index", "Home");
}
or, it you use T4MVC (and you should ;-))
public ActionResult MyAction() {
return RedirectToAction(MVC.Home.Index());
}
Do not put the if statement in the view - that's not the MVC way. It is the responsibility of the controller to decide whether to redirect to a different view.
Try like this:
<script type="text/javascript">
// Make sure the LastId variable is defined
var LastId = '123';
<% if (BreakCount >= 8) { %>
var url = "http://192.168.1.109/MWT/Taglist/ShowMap" + LastId;
window.location.replace(url);
<% } %>
</script>
Try this:
<script type="text/javascript">
var id = '123';
location.href = "http://192.168.1.109/MWT/Taglist/ShowMap/" + id;
</script>
Try like this :
top.location.href = "/url";