Why ASP.Net MVC Session value is null in controller ? - asp.net-mvc

I have a controller that called "Login"
this method is in Login
public bool IsAuthenticated()
{
if (Session != null && Session["UserRole"] != null)
{
return true;
}
return false;
}
I set session values in Login other method.(ex: LogOn)
But in X Controller
public ActionsResult Index() {
if(!login.IsAuthenticated()){
return RedirectToAction("Index","Login");
}
return View();
}
in this method is null.
If I controll Session in Controller Methods,I think this isn't functional
public ActionsResult Index() {
if (Session == null && Session["UserRole"] == null)
{
return RedirectToAction("Index","Login");
}
return View();
}
Note:I don't Use ASP.net MVC Membership API

Related

Adding Roles to existing project

im confused about adding roles to existing project which i set the Authentication to "No Authentication".
i have database in mssql with field only "username" and "password". And i use it for authentication. My question is how i adding roles like "administrator" or "userA" or "guest" for Authorization. Im so new to Mvc. Thanks!
this is my controller code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace _3131.Controllers {
public class HomeController : Controller {
[Authorize]
public ActionResult Index(string button) {
ViewData["username"] = User.Identity.Name;
var viewdata = Convert.ToString(ViewData["username"]);
if(viewdata == "admin") {
return View();
}else if(viewdata == "userA") {
return View();
} else if(viewdata == "userB") {
return View();
} else {
return View();
}
}
[Authorize]
public ActionResult About() {
ViewData["username"] = User.Identity.Name;
var viewdata = Convert.ToString(ViewData["username"]);
if(viewdata == "admin") {
return View();
}else {
return View("Error");
}
}
[Authorize]
public ActionResult UserA() {
ViewData["username"] = User.Identity.Name;
var viewdata = Convert.ToString(ViewData["username"]);
if(viewdata == "userA" || viewdata == "admin") {
return View();
}else {
return View("Error");
}
}
[Authorize]
public ActionResult UserB() {
ViewData["username"] = User.Identity.Name;
var viewdata = Convert.ToString(ViewData["username"]);
if (viewdata == "userB" || viewdata == "admin") {
return View();
} else {
return View("Error");
}
}
[Authorize]
public ActionResult UserC() {
ViewData["username"] = User.Identity.Name;
var viewdata = Convert.ToString(ViewData["username"]);
if (viewdata == "userC" || viewdata == "admin") {
return View();
} else {
return View("Error");
}
}
}
}
There are multiple ways to achieve this.
1.You can create a Generic Principal, that accepts two parameters identity and roles, The Authorize attribute looks at the principal
attached to HttpContext to authorize the request.
https://www.sharpencode.com/article/MVC/filters-in-asp-net-mvc/authorize
2. You can create a Custom Role provider, which is the easiest.
Role Provider in MVC
3. You can override Authorize Attribute

Can't get action result to run if statement and go to logged in section

For some reason, The users in db.users.Where()is not working like the rest of the users in the code. Need some assistance to make it get to the logged in stage.
public ActionResult Login()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(User users)
{
if (ModelState.IsValid)
{
using(DataContext db = new DataContext())
{
var obj = db.users.Where(u => u.Username.Equals(users.Username) && u.Password.Equals(users.Password)).FirstOrDefault();
if (obj != null)
{
Session["UserID"] = obj.UserID.ToString();
Session["Username"] = obj.Username.ToString();
return RedirectToAction("LoggedIn");
}
}
}
return View(users);
}
public ActionResult LoggedIn()
{
if (Session["UserID"] != null)
{
return View();
}
else
{
return RedirectToAction("Login");
}
}

I am not able to get the User.Identity.Name after redirected from controller in Mvc

In the 1st example:-
i am assigning User.Identity.Name value to the variable id. i am able to get the value after that i am Redirecting to some other view here i am using Redirect(ReturnUrl) now i am able to get the User.Identity.Name value in the other controller(Redirected view) also
But in the 2nd example :-
i am assigning User.Identity.Name value to the variable id i am able to get the value after that i am Redirecting to some other view here i am using return Redirect(ReturnUrl);when i am using return Redirect(ReturnUrl);am not able to get the User.Identity.Name value in the Redirected url
Example 1:-
public ActionResult SignIn(string ReturnUrl)
{
if (ReturnUrl == "/" || string.IsNullOrEmpty(ReturnUrl))
{
ReturnUrl = "/Dashboard";
}
var id=HttpContext.Current.User.Identity.Name;
Response.Redirect(ReturnUrl);
return View();
}
Example 2:-
public ActionResult SignIn(string ReturnUrl)
{
if (ReturnUrl == "/" || string.IsNullOrEmpty(ReturnUrl))
{
ReturnUrl = "/Dashboard";
}
var id=HttpContext.Current.User.Identity.Name;
return Redirect(ReturnUrl);
}
My Controller:- In this function if i am return Redirect(ReturnUrl); i am not able to get the User.Identity.Name value in CompanyRequired filter if i am using Response.Redirect(ReturnUrl); return View(); then able to get the User.Identity.Name value in CompanyRequired filter but i have to use return Redirect(ReturnUrl);
[HttpPost]
public async Task<ActionResult> SignInCallback()
{
var token = Request.Form["id_token"];
var state = Request.Form["state"];
var claims = await ValidateIdentityTokenAsync(token, state);
string ReturnUrl = state.Substring(state.IndexOf('?') + 1);
var id = new ClaimsIdentity(claims, "Cookies");
Request.GetOwinContext().Authentication.SignIn(id);
if (ReturnUrl == "/" || string.IsNullOrEmpty(ReturnUrl))
{
ReturnUrl = "/Dashboard";
}
var Id = User.Identity.Name;
return Redirect(ReturnUrl);
}
View:- Here i control will go to the CompanyRequired filter there i need a User.Identity.Name value in that i am getting value null
[Authorize,CompanyRequired]
public class DashBoardController : BaseController
{
public ActionResult Index()
{
return View();
}
}
CompanyRequired Filter:-
public class CompanyRequiredAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var coCookie = filterContext.HttpContext.Request.Cookies["CoId"];
if (coCookie == null)
{
var Id= HttpContext.Current.User.Identity.Name.Int(); **//here i need to get the value but i am getting null value**
IdNmList cos = new EmployeeDAL().GetCompany(Id);
if (cos.Count == 0)
{
filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary
{
{ "controller" , "Company"},
{ "action" , "Add"}
});
}
else if (cos.Count == 1)
{
filterContext.HttpContext.Response.Cookies.Add(new HttpCookie("CoId", cos[0].Id.ToString()));
}
else
{
filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary
{
{ "controller", "Company" },
{ "action", "Select" },
{ "ReturnUrl", filterContext.HttpContext.Request.RawUrl }
});
}
}
base.OnActionExecuting(filterContext);
}
}

Refresh a page in MVC

How to refresh the current page in MVC.
[HttpGet]
public ActionResult Request()
{
if (Session["type"] != null && Session["resulttype"] != null)
{
return View();
}
else
{
return null;
}
}
I want to refresh my page in else part. That is when return null value.
You can use Request.UrlReferrer.ToString()
[HttpGet]
public ActionResult Request()
{
if (Session["type"] != null && Session["resulttype"] != null)
return View();
else
return Redirect(Request.UrlReferrer.ToString());
}
You can use the following code in asp.net core
public IActionResult Index(){
return Redirect($"{Request.Path.ToString()}{Request.QueryString.Value.ToString()}");
}
Just Redirect to the Action you want to redirect to. It will refresh your page.
[HttpGet]
public ActionResult Request()
{
if (Session["type"] != null && Session["resulttype"] != null)
{
return View();
}
else
{
return RedirectToAction("Request");
}
}
You can use location.href = location.href; in Javascript code after calling a buttonclick or after a action method call like.
$('#btnme').click(function () {
location.href = location.href;
}

Session is null in HttpHandler but not in MVC Controller

I have security in my MVC application set up with an authorize attribute...
public class UserLoggedInAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Session["UserId"] == null)
{
var values = new { controller = "Home", action = "Index" };
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(values));
}
}
}
Then I also have a .ashx HttpHandler which is called by jQuery upload control....
public class UploadFile : IHttpHandler, IReadOnlySessionState
{
...
private bool EnsureSecureTransaction(HttpContext context)
{
if (context.Session["UserId"] == null)
{
return false;
}
else
{
return true;
}
return true;
}
}
When EnsureSecureTransaction() gets called the session is coming back null. But session that is read in my MVC action its not. I notice that I'm taking session from the filterContext though.
I have tried to change all the code to try and reference HttpContext.Current.Session like this
[HttpPost]
public ActionResult Logon(AdminModel model)
{
if (model.UserName == "x" && model.Password == "x")
{
HttpContext.Session["UserId"] = "true";
return RedirectToAction("CreateBlog", "Blog");
}
return View;
}
private bool EnsureSecureTransaction(HttpContext context)
{
if (context.Session["UserId"] == null)
{
return false;
}
else
{
return true;
}
return true;
}
But basically when I hit the EnsureSecureTransaction() block its still saying my Session["UserId"] is null and therefor not autehenticating the call to the .ashx file correctly.
Anyone know why this is? Whats the actual difference between AuthorizationContext and HttpContext with regards to the session they carry and how do I get round this problem?

Resources