How to check which link user had used? - c#

Hello I have online course website. I have authorizecontroller for admin area and you can access there by typing www.name.com/area then you log in and go to the admin area. I also need students to log in here but they should go to different link like wwww.name.com./LoginStudent. So the students will come from the page www.name.com/Course/Detail and in the detail page button leads him/her to log in controller in admin area. So I want to check if user came from www.name.com/Course/Detail I want redirect him/her to wwww.name.com./LoginStudent how can I control where did he come from ?
here is my log in controller ;
public ActionResult Login(string returnUrl, LoginModel input)
{
if (!ModelState.IsValid)
{
ShowErrorMessage("Hatalı Giriş Yaptınız.");
return View(input);
}
var yonetici = Db.Members.FirstOrDefault(p => p.Mail == input.EMail && p.Active == true && p.Authority == Authority.Admin);
if (yonetici == null)
{
ShowErrorMessage("Hatalı E-Posta adresi.");
ModelState.AddModelError("EMail", " ");
return View(input);
}
if (yonetici.ValidatePassword(input.Sifre) == false)
{
ShowErrorMessage("Hatalı şifre");
ModelState.AddModelError("Sifre", " ");
return View(input);
}
I dont want to send login page by pressing button because I'm using [Authorize] so it checks if loged in before or not
well I did this to make it easy but how to make it work on page load
var itemUrl = Request.Url.ToString();
if (itemUrl.Contains("Participant"))
{
ShowErrorMessage("Hatalı Giriş Yaptınız.");
return View(input);
}

You can find the previous page (referrer) using HttpContext.Current.Request.UrlReferrer.ToString();
Then show appropriate login screen.

You will need to save this kind of the information somewhere, maybe on a database? If so, you use a column at the database to save the Source Redirect, so You can query and measure on the future. You can pass it before redirect.

Related

C# MVC ActionLink clear session before reloading page

I have a simple form page, where user can fill some data. After I press post, I need all that data to remain as it is, so if user wants to change data, he/she can. After I save data I store Client object in Session and every time I press Save button, I check if there is user already in Session.
Now I have #Html.ActionLink("New client", "NewUser");, that I press, when I want to create new user. So this link would reload the page and clear that Session.
Note that "New user" should redirect to Index instead, but I managed to get it to work like that, but is not valid way to do so.
Controller code:
public ActionResult Index()
{
return View(_vm);
}
public ActionResult NewUser()
{
Session["newClient"] = null;
return RedirectToAction("Index");
}
clearing the session can only done on backend so you have to make action to clear the session but you dont need return RedirectToAction("Index"); instead return the view
public ActionResult NewUser()
{
Session["newClient"] = null;
return View("Index",_vm);
}
since you are redirecting to the index view for creating new user

Redirection to a web page C# API

I have little problem with my api and its account-management. Whenever a user creates a new account, it has to be confirmed by clicking on a link that is sent by email. That works perfectly fine.
However, when the user clicks on the link, it opens up a blank browser window. Now I'd like to redirect the user to a webpage that offers instructions for the application. After a bit of research, I found the "redirect(string url)" command.
[HttpGet]
[AllowAnonymous]
[Route("ConfirmEmail", Name = "ConfirmEmailRoute")]
public async Task<IHttpActionResult> ConfirmEmail(string userId = "", string code = "")
{
if (string.IsNullOrWhiteSpace(userId) || string.IsNullOrWhiteSpace(code))
{
ModelState.AddModelError("", "User Id and Code are required");
return BadRequest(ModelState);
}
IdentityResult result = await this.AppUserManager.ConfirmEmailAsync(userId, code);
if (result.Succeeded)
{
Redirect("http://www.orf.at");
return Ok();
}
else
{
return GetErrorResult(result);
}
}
The address should only be an example. Whenever one clicks on a link, however, the browser still opens a blank tab. Is there a possibility to avoid that? The best solution would be to redirect the user to another site. But if that does not work, can it somehow be prevented that a new window is opened up?
Instead of returning Ok() return Redirect("http://www.orf.at");
if (result.Succeeded)
{
return Redirect("http://www.orf.at");
}
else
{
return GetErrorResult(result);
}

ASP.NET MVC forms authentication equivalent

when I was writing ASP.NET applications I used the Forms Authentication with my custom login page, like so:
Once login is a success I checked him as authenticated:
FormsAuthentication.RedirectFromLoginPage(userId.ToString(), true);
In order to check if a user is logged in, I had a class that inherited from a base page and all pages inherited from it, which contained a method that returned a bool after checking if the user is authenticated, with the following command:
return HttpContext.Current.User.Identity.IsAuthenticated;
Now, I'm doing an ASP.NET MVC application, and was wondering what is the best was to do that on MVC?
Thanks
ok MVC is very simple and similar
for your question you can use like .......
in your controller
public ActionResult LogOn()
{
return View();
}
//
// POST: /Account/LogOn
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var userInfo = new UserInfo()
{
UserName = model.UserName,
Password = model.Password,
};
var service = new CSVService();
if(service.ValidateUser(userInfo))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return Redirect("~/");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
The best way to authenticate website / web-application is using the Membership which is provided by Microsoft built in for Easy-ness .
From this you can do following things(features)
it maintains Log-in status (you don't have to bother about Authentication).
It allows to provide Roles & Users and Assigning permission who can see which page
(Page Restriction)
It provides built-in Stored Procedures and UI tools like Log-in, Log-out,user,Password Recovery, Etc elements. & Highly secure (Hack-Proof)
for more info:
Walk through Membership (MSDN)

Fixing the action back to an account page in asp.net mvc application

I have an asp.net mvc4 application, in which i have to logout from an account :
if (_fonction == "User")
{
if (_is_admin == true) return RedirectToAction("Index");
else
{
Session["user"] = _u;
return RedirectToAction("Index", "User");
}
}
in the controller User
public ActionResult Index()
{
if (Session["user"] == null) return RedirectToAction("Index", "Home");
return View(Session["user"]);
}
the action Logout
public ActionResult Logout()
{
if (_is_admin) { Session["user"] = null; return RedirectToRoute("Administration"); }
else { Session["user"] = null; return RedirectToAction("Index", "Home"); }
}
i do this : i log in to a user account then i disconnect so i'am in the home page , then i click into the back button of the browser i got the page of the account. When i refresh i returned to the home page. i think that the problem is in the cache and i don't think that make it null is a good idea .
So how can i fix this problem?
You can try to add [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] as an attribute to your User controller's Index action to force non-cached results.
But I would strongly suggest to just use AuthorizeAttribute because this will prevent unauthorized web requests done on a specific view. The benefit of using this is that you still give the users the liberty to cache your views and be secured at the same time.
if you do not want to clean your cache then below is the javascript which helps you to hard refresh your page on click of the browser back button
if (window.name != "") { // will be '' if page not prev loaded
window.name = ""; // reset to prevent infinite loop
window.location.reload(true);
}
window.name = new Date().getTime();
put the above "javascript" code on your page. so, it will hard refresh your page.

Prevent back button

I am using Razor on ASP.NET MVC with C#.
I am calling an external web page to process a credit card and it returns to me. I then display a receipt.
I'd like to prevent them from going back to the previous screen.
I do not have an underlying cs page, like asp since these are .cshtml files, to grab the event.
This receipt page is a View so I cannot put JavaScript in the header since it would affect every page using it.
Anyone know how I prevent the back button in this circumstance?
One possibility is to exclude the page you don't want to get back to from caching on the client. This could be done by setting the proper response headers. Here's an example with a [NoCache] custom action filter which you could use to decorate the corresponding controller action.
Firstly, if the previous page posted data to the server, best to Redirect(...) to another action after the successful processing, to avoid the data being resubmitted on "Refresh".
Then also set the page to expire, so the back button doesn't work:
https://stackoverflow.com/a/5352953/864763
You're asking the wrong question. Don't try to disable "back" on the client. This will be doomed to fail; you may be able to make it harder, but you'll never win that fight. Instead you should re-write the particular page that you have such that it will only ever process the credit card once. You should (on the server) "remember" that you've processed the credit card so that if the user goes back to the page to resubmit it you can just give them an error message saying "you have already submitted this information, you cannot submit this request twice".
Now, there are several ways of accomplishing this general goal, and some are better than others, but that's the goal you need to strive towards.
One way to do this is to go to every page that will redirect the user to this credit card form; just before submitting the request add something to that user's session (i.e. "pendingCreditCardSubmission" = true) Once they submit that request you then check for that session variable. If it's true, submit the request and set it to false, if it's false or not there then send an error message to the user.
This is how we did it:
public class NoBackFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.HttpContext.Response.ExpiresAbsolute = DateTime.Now;
filterContext.HttpContext.Response.Expires = 0;
filterContext.HttpContext.Response.CacheControl = "no-cache";
filterContext.HttpContext.Response.Buffer = true;
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow);
filterContext.HttpContext.Response.Cache.SetNoStore();
filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
if (!filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.HttpContext.Request.HttpMethod != "POST" && !filterContext.Controller.ControllerContext.IsChildAction)
{
var after = filterContext.HttpContext.Request.RawUrl;
var session = GetSession(filterContext);
if (session["Current"] != null)
{
if (session["Before"] != null && session["Before"].ToString() == after)
filterContext.HttpContext.Response.Redirect(session["Current"].ToString());
else
{
session["Before"] = session["Current"];
session["Current"] = after;
}
}
else
{
session["Current"] = after;
}
}
base.OnActionExecuting(filterContext);
}
private HttpSessionStateBase GetSession(ActionExecutingContext context)
{
return context.HttpContext.Session;
}
}
After this you can implement it either in the general scope or in the controller scope.
It has been long since this was asked, but my fix was adding the [NoCache] above the WebPageController class.
[NoCache]
public class WebPageController : Controller
{
public JsonResult JsonError(Exception exception)
{
if (exception == null) throw new ArgumentNullException("exception");
Response.StatusCode = 500;
return new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new
{
error = true,
success = false,
message = exception.Message,
detail = exception.ToString()
}
};
}
in MVC aspnet framework, you may choose to RedirectToActionPermanent
Which then it tells the browser 301 response code.
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.controllerbase.redirecttoactionpermanent?view=aspnetcore-5.0

Categories

Resources