i have used custom Membershipprovider and roleprovider class in my asp.net mvc4 application.
this code works fine :
[OutputCache(Duration =0, NoStore= true)]
public class HomeController : Controller
{
public ActionResult Login(string ReturnUrl)
{
return View(new User());
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(User u, string ReturnUrl) {
if (Membership.ValidateUser(u.login, u.password))
{
FormsAuthentication.SetAuthCookie(u.login, false);
if (Roles.GetRolesForUser(u.login).Contains("user")) return RedirectToAction("Index");
else return RedirectToAction("Common");
}
else {
return View(u);
}
}
[Authorize(Roles = "user")]
public ActionResult Index()
{
return View();
}
[Authorize(Roles="admin")]
public ActionResult Common()
{
return View();
}
public ActionResult SignOut()
{
FormsAuthentication.SignOut();
return RedirectToAction("Login");
}
}
But i need to verify if the existence of a connected user in the Login action
public ActionResult Login(string ReturnUrl)
{
//verification and redirection if connected
return View(new User());
}
I need to know:
What are the different manners to do that?
What is the best one?
you can check this way:
if (User.Identity.IsAuthenticated)
{
// user logged in already
}
Related
I have 2 controllers which both display the same view, the first shows a specific SSO provider and the other shows all SSO providers. When posting the login form and something goes wrong, the [HttpPost] controller either returns /account/login or /account/login?code=Facebook but both are the 2nd view. Is it possible to return the /account/{code}/login view if the code is not null and return the other view if it is? With either view returned I need the model and any errors to be kept when the view is returned.
[HttpGet]
[Route("/account/{code}/login")]
[AllowAnonymous]
public async Task<IActionResult> Login(string code, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
ViewData["Code"] = code;
LoginViewModel model = new LoginViewModel();
model.SocialLogins = new List<string> { code };
return View(model);
}
[HttpGet]
[Route("/account/login")]
[AllowAnonymous]
public async Task<IActionResult> Login(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
LoginViewModel model = new LoginViewModel();
model.SocialLogins = _socialLogins;
return View(model);
}
[HttpPost]
[AllowAnonymous]
[Route("/account/login")]
[Route("/account/{code}/login")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string code = null, string returnUrl = null)
{
ViewData["Code"] = code;
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
//login code
}
return View(model);
}
public class LoginViewModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
public List<string> SocialLogins { get; set; }
}
I am new to learn filters in mvc. I create a Authorization filter in my project.
Accountcontroller
public class AccountController : Controller
{
//
// GET: /Account/
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Logins()
{
string username = Request["username"];
string password = Request["password"];
Session.Add("username", username);
Session.Add("password", password);
return Redirect("/Home");
}
}
public class CustomAuthorizationAttribute : FilterAttribute, IAuthorizationFilter
{
void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)
{
try
{
string username = HttpContext.Current.Session["username"].ToString();
string password = HttpContext.Current.Session["password"].ToString();
if (username == password)
{
HttpContext.Current.Response.Redirect("/Home");
}
else
{
HttpContext.Current.Response.Redirect("/Account/login");
}
}
catch
{
HttpContext.Current.Response.Redirect("/Account/login");
}
}
}
Homecontroller
public class HomeController : Controller
{
//
// GET: /Home/
[CustomAuthorization]
public ActionResult Index()
{
return View();
}
}
But now i am checking same string as username and password when i run this project if the username and password is correct home page is reloading again and again.
Inherit from Authorization attribute and override default behavior
Simple implementation would be like this
public class OptionalAuthorizeAttribute : AuthorizeAttribute
{
public OptionalAuthorizeAttribute()
{
}
protected override bool AuthorizeCore(HttpContext httpContext){
string username = HttpContext.Current.Session["username"].ToString();
string password = HttpContext.Current.Session["password"].ToString();
if (username == password)
{
return true;
}
return base.AuthorizeCore(httpContext);
}
}
And then you could override behavior of AuthorizeAttribute.HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext)
Side note: I wrote this answer from mobile phone, so please double check for syntax errors when pasting to visual studio
I am new to MVC5 and i am trying to work on 'search' functionality. my aim is get data from a dataservice.(that is, i enter data into a form and hit the search button, if theres a record it displays data).
I have created a dependency to mock the data(dummy data). How do i wire up my code to the contoller to achieve my purpose?. Please advice Thank you.
Heres my controller and my mock:
public class SearchController : Controller
{
private readonly ISearchResultsService _resultsService;
public SearchController() : this(DependencyFactory.NewResultsService())
{
}
public SearchController(ISearchResultsService resultsService)
{
_resultsService = resultsService;
}
// GET:Search
public ActionResult Index()
{
return View();
}
// GET: Search/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: Search/Create
public ActionResult Create()
{
return View();
}
// POST: Search/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return();
}
catch
{
return View();
}
}
//[HttpPost]
//public ActionResult Index(SearchCriteria data)
//{
// var data = this._resultsService.FindClaims(data);
// return View(data);
//}
[HttpPost]
public ActionResult Index()
{
return View();
}
// GET: Search/Edit/5
public ActionResult Edit(int id)
{
return View();
}
// POST: Search/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Search/Delete/5
public ActionResult Delete(int id)
{
return View();
}
// POST: Search/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
public static class DependencyFactory
{
public static ISearchResultsService NewResultsService()
{
return new MockSearchResultsService();
}
}
public interface ISearchResultsService
{
List<Person> FindClaims(string firstName, string lastName);
}
public class MockSearchResultsService : ISearchResultsService
{
public List<Person> FindClaims(string firstName, string lastName)
{
return new List<Person>(new []{new Person{FirstName = "John", LastName = "Doe"}});//throw new NotImplementedException();
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
I recommend you to use some IoC container like http://autofac.org. You can configure your container and register your service like this way:
builder.RegisterType<MockSearchResultsService>().As<ISearchResultsService>()
All your dependencies will be automatically resolved:
public class SearchController : Controller
{
private readonly ISearchResultsService _resultsService;
public SearchController(ISearchResultsService resultsService)
{
_resultsService = resultsService;
}
}
Note that there is many IoC containers you can use. Try to search more about AutoFac, Ninject or Castle Windsor.
I want to send dropdownlist selected value from Controller to another controller
and recuperate that value (i know how to send it ) but i dont know how to recuperat it
controller 1:
public class PosteController : Controller
{
[HttpPost]
public ActionResult Index(CandidateModel Id)
{
return RedirectToAction ("Inscription","Candidate",Id);
}
public class CandidateController : Controller
{
[HttpPost]
public ActionResult Inscription()
{
...........
}
Method 1:
Using Object Route :
public class PosteController : Controller
{
[HttpPost]
public ActionResult Index(CandidateModel Id)
{
return RedirectToAction ("Inscription","Candidate",new{ dropdownval=Id.val,Id });
}
public class CandidateController : Controller
{
public ActionResult Inscription(int? dropdownval)
{
...........
}
Method 2:
Using TempData:
public class PosteController : Controller
{
[HttpPost]
public ActionResult Index(CandidateModel Id)
{
TempData["Id"]=Id.val;
return RedirectToAction ("Inscription","Candidate");
}
public class CandidateController : Controller
{
public ActionResult Inscription()
{
var id=TempData["Id"];
...........
}
In above examples Id.val is the selected dropdown value.
You can use TempData for this.
[HttpPost]
public ActionResult Index(CandidateModel Id)
{
TempData["var"] = id;
return RedirectToAction ("Inscription","Candidate",Id);
}
public ActionResult Inscription()
{
var id = TempData["id"] as CandidateModel;
}
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
//var clinicbusiness = new ClinicBusiness ();
return View();
}
[HttpPost]
public ActionResult ValidateCommand()
{
var pa = new PaymentView();
if (ModelState.IsValid)
return View("ValidateCommand");
else
return View();
}
public ActionResult RedirectFromPaypal()
{
return View("RedirectFromPaypal");
}
private ActionResult View(Func<ActionResult> RedirectFromPaypal)
{
throw new NotImplementedException();
}
this is my controller and i have a problem taking items from A CART
how to add cart items to a controller n accumulate price
using payfast checkout button