MVC 4 code file (.cs) redirect to an action - session

I have created a .cs file where I am checking the session values.
I am using session like below
HttpContext.Current.Session["usrprof"]
It is written in a simple .cs file.
I can use if I am in controller but can I use it in normal .cs file
Can I use redirect to action if I don't get anything in the Session
if (HttpContext.Current.Session["usrprof"] == null)
//redirect to action.

You can simply use Redirect from Response object
if (HttpContext.Current.Session["usrprof"] == null)
{
HttpContext.Response.Redirect("/Controller/Action");
}
Hope it helps

You can use Session in your CS files, yes as long as you have access to the Session object.
To use RedirectoAction you can do:
public ActionResult TestMethod()
{
if (HttpContext.Current.Session["usrprof"] == null) {
return RedirectToAction("Index");
}
return View();
}
Which will check if usrprof is null, if it is redirect them to Index (Or your view). Else if userprof is not null, return the default view.

HttpContext.Current is a static available to all code - will be null when not run under a web context i.e. a web app.

if you want to redirect from cs file you have to redirect from response object as shown in below piece of code
HttpContext.Current.Response.Redirect(~/Account/Login, true);
In the above code Account is Controller name is Login is Action

Related

Why am I automatically pushed to login page when a user is unauthenticated by calling the Web API?

I am using MVC 6 web api and I have a method (shown below). When the user is not authenticated (logged on) and makes the call (example url: https://localhost:44338/api/account/Test), they get automatically pushed to url:
https://localhost:44338/Account/Login?ReturnUrl=%2Fapi%2Faccount%2FTest
BUT this is a web api project and does not have any views (such as im automatically getting pushed to here).
Code:
[HttpGet("test")]
[Authorize]
public async Task<IActionResult> Test()
{
return Json("success");
}
Why am I getting automatically pushed to the login page? I've NOTHING in my startup.cs or web.config that specifies this. It seems like default behaviour? How do I disable this so I just get the 401 status?
Thanks in advance!
For convenience, here's the solution that worked for me:
services.Configure<IdentityOptions>(o =>
{
o.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents()
{
OnRedirectToLogin = ctx =>
{
if (ctx.Response.StatusCode == (int)HttpStatusCode.Unauthorized)
{
return Task.FromResult<object>(null);
}
ctx.Response.Redirect(ctx.RedirectUri);
return Task.FromResult<object>(null);
}
};
});
I was pointed to this article: mvc6 unauthorized results in redirect instead by #TrevorWard
ASP.NET automatically redirects to the login page, if you have AuthorizationAttribute defined in your App_Start/FilterConfig.cs, see if AuthorizeAttribute() is defined. If it does, remove it.
Check if you have App_Start/Startup.Auth.cs. If it does, delete it.
If Startup.cs is decorated with the attribute [assembly: OwinStartupAttribute(typeof(FleetSys.Startup))], remove that attribute.
You are probably using wrong Authorize attribute.
In MVC, you should use System.Web.Mvc.AuthorizeAttribute and that one will redirect.
In Web API, you should use System.Web.Http.AuthorizeAttribute and that one will return 401 status code.

Stoping users from accessing an ActionResult but allow it to be acessed via Html.Action/RenderPartial code and AJAX calls

I have some ActionResults that I don't want an user to be able to directly access but I need to be able to call them from views using #Html.Action, #Html.RenderPartial, and AJAX. I was using the ChildActionOnly but if I use that I can't access the page via AJAX. If I remove the ChildActionOnly attribute I can call it by AJAX but I can also call it directly by URL which is what I don't want happening. Is this possible to do of do I have to leave the ActionResult opened?
You can have the public action with a parameter to indicate whether or not the method should be executed like
public ActionResult DoSomething(bool shouldBeExecuted=false)
{
if (shouldBeExecuted == false)
{
throw new UnauthorizedAccessException("The action is not available");
}
ViewBag.Title = "Test Page";
return View();
}
And when you create a link for the action, just pass the "true" as a query string value.

Avoiding unauthorized access to a page by changing the URL query parameter in mvc3

I'm new in mvc and I have a question: If I have Index page (page with list of some object this is url http://localhost:6384/admin/) and I have actionlink button on which when user clicks he gets details of that object this is url http://localhost:6384/Admin/Apartman/details/1.
ID of obejct is 1, but if user change value 1 to some other value he will get some other object which maybe he shouldn't be able to see it.
What can I do to protect application?
The way i do it is simply checking whether the user has access to that object.
public ActionResult EditProfile(int id)
{
ApartmentViewModel objVM=MyService.GetApartment(id);
if(objVM.CreatedById==id)
{
return View(objVM);
}
else
{
return View("UnAuthorized");
}
}

Persisting Data from one controller to another

Hey guys,
What is the best mechansims for persisting viewmodel data from one controller to another.
For instance
return RedirectToAction("SomeAction", "SomeController");
I need to have some data from the previous controller available to the new controller I am redirecting to.
If you are not passing an object or something complex, make use of parameters. Just make sure redirected action gets parameters to display what it should.
return RedirectToAction("SomeAction", "SomeController",new { id=someString} );
Get the parameter in the action:
public ActionResult SomeAction(string id)
{
//do something with it
}
#Ufuk Hacıoğulları: You can't share information between 2 controllers using ViewData. ViewData only shares information between Controller and View.
If you need to share complex information between multiple Controllers while redirection, use "TempData" instead.
Here is how you use "TempData" - http://msdn.microsoft.com/en-us/library/dd394711.aspx
A redirect is going to send an http response to the client that directs it to then make a new http request to /SomeController/SomeAction. An alternative would be for you to call a method on your other controller directly... new SomeController().SomeAction(someData) for example.
I think this will be helpfull to you to pass value from one action to another action .
public ActionResult ActionName(string ToUserId)
{
ViewBag.ToUserId = ToUserId;
return View();
}
public ActionResult ssss(string ToUserId)
{
return RedirectToAction("ActionName", "ControllerName", new { id = #ToUserId });
}

Redirect in onSubmit() method of simpleformcontroller

I am new to spring framwork and using 2.5 version.
My requirement is that based on some value of command object in submit method I have to redirect the user to url /out.This is not defined as any view.But used for logout.
Ex.http://127.34.22.22:8080/abc is the invoking url and the url after redirect needed is the http://127.34.22.22:8080/out.
I tried redirect it is working only when I hardcode the whole url,but unable to redirect at runtime.
if(attribute is true){
return new ModelAndView("http://127.34.22.22:8080/out");
}else{
return new ModelAndView(getSuccessView());
}
Above code is working but I don't want to hardcode whole url.
Thanks in advance.
ModelAndView expect an VIEW name but not an URL. (ModelAndView(String viewName))
What you need is to pass an an RedirectView as parameter to ModelAndView(View view)
Example:
if(attribute) {
return new ModelAndView(new RedirectView("http://127.34.22.22:8080/out");
} else {
...
}

Resources