Maintain the model lifetime in MVC application - c#

I am new to MVC and I have very simple problem.
When user login to my application I need to create a specific object (model) for the user for eg UserObject.
This object is unique to current logged in user and should only be disposed when user click on logout.
I don’t know how to maintain the lifetime of the object. As if I create object in Action method of controller class then as soon as the request is finished I lose the reference of the object.
How this should have been done?

The lifetime of your models are only going to be as long as the request. So each time the user goes to another page or refreshes, the MVC framework is going to instantiate a new controller (and model within). Otherwise your server would have a ton of static objects floating around in memory which would use up a lot of resources and wouldn't scale.
In order to manage state, you are going to need to use other methods such as sessions/cookies and a database.
So let's say the user logs in via /User/Login. This routes the request to an action named UserController.Login().
Inside this action, it instantiates a UserModel.
public ActionResult Login(string username, string password) {
var userModel = new UserModel();
if (userModel.Authenticate(username, password)) {
// Setup your session to maintain state
Session["username"] = username;
} else {
return View("Login");
}
return View("LoginComplete");
}
You might want the user model to actually create the session, but I've shown it here for clarity.
The user model authenticates the user, and then you create a session just like you would in a traditional non-MVC site.
Then in subsequent requests, you will want to authorize the user, and use any session data you have to retrieve state information.
public ActionResult SuperSecretPlace() {
var userModel = new UserModel();
string username = Session["username"]
var user = userModel.GetUserByUsername(username);
if (user == null) throw new HttpException(401, "User is not authorized.");
return View("SuperSecretPlace", user);
}
In the action above, the UserModel might do something like query a database to retrieve the user's data so you can pass it in to the corresponding view.
If you want to make life easier, you might want to just use .NET's built in forms authentication:
http://www.codeproject.com/Articles/578374/AplusBeginner-splusTutorialplusonplusCustomplusF
For more info about the lifecycle of MVC:
http://www.dotnet-tricks.com/Tutorial/mvc/TbR0041112-Asp.net-MVC-Request-Life-Cycle.html
http://www.asp.net/mvc/overview/getting-started/lifecycle-of-an-aspnet-mvc-5-application

Actually what you are trying to achieve is passing model from controller to controller which is not possible. When an action is executed the context of the model object is disposed at the view and it can cannot be passed from controller to controller. You have to create a new object repopulate it and use it to achieve the goal in different controller.If you need the data to be persisted you can use sessions but still you need to create an object of the model in every controller.
The following image is for your reference as to see what to use when passing data between model-view-controller. Please feel free to ask if you need more information on this.

As opposed to the other aswers I would not use session as it has quite some disadvantages (scalability, pessimistic concurrency which blocks concurrent calls, app pool recycling...). Why you should not use session is documented in a lot of places like here or here.
Instead, I would store it in a cookie.
However, be sure to not store confidential or sensitive data. Whatever you use (cookies or session), it can be tampered with or stolen. If you are dealing with sensitive information, you need other solutions. Read also more about secure cookie solution here.

Related

How to pass fragile data e.g connection string from one controller to another

Im new to asp.net core and I was trying to develop an online SQL database manager, that will work on any SQL database, after passing: ServerAddress, Login, Password and DatabaseType (my ConnectionInformation model).
Something like SSMS but online.
I want to pass my ConnectionInformation model from Login controller to Database controller.
Redirecting to action uses query string which exposes all of my data.
TempData only accepts strings and converting my model to json isn't the most elegant way to solve this problem.
Login Controller:
public class LoginController : Controller
{
private readonly ILoginLogic _loginLogic;
public LoginController(ILoginLogic loginLogic)
{
_loginLogic = loginLogic;
}
[HttpGet]
public IActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Index(ConnectionInformationViewModel connectionViewModel)
{
if (!ModelState.IsValid)
return View();
ConnectionInformation connection = Mapper.Mapper.ConnectionInformationMapper(connectionViewModel);
var connectionSuccess = _loginLogic.ConnectToDatabase(connection);
if (connectionSuccess)
return RedirectToAction("Index", "Database", connection);
else
return View(); // TODO: Return view with error or handle it in js
}
}
Database Controller:
public class DatabaseController : Controller
{
private readonly IDatabaseLogic _databaseLogic;
public DatabaseController(IDatabaseLogic databaseLogic)
{
_databaseLogic = databaseLogic;
}
public IActionResult Index(ConnectionInformation connection)
{
var databases = _databaseLogic.GetDatabases(connection);
return View(databases);
}
}
Prehaps my approach is totally wrong. My main goal is to check if I can connect to database, and if I can I want to perform query operations on that Database untill user logs out.
Well, simply, you have to persist the information some way. In that regard, there's a number of options. You could persist it in local storage on the client and actually pass it back with each further request. That works better for SPA-style apps, where you're pretty much doing everything via AJAX, though. Another technically client-side storage mechanism would be setting a session cookie with the posted connection information. Here I'm talking about explicitly setting and reading from a cookie with a "session" lifetime, not using sessions.
Or you can can actually use a true session, i.e. Session. TempData is basically just Session anyways, but here it would be inappropriate as you'd then need to ensure that the TempData is kept every time it's accessed or it won't survive the next request. If you're doing that, then you might as well just use Session and not have to worry about it.
Serialization is pretty much required no matter what you do. There's no way to persist an actual C# object instance, so you're either going to have to write it to a relational store like a database or serialize it to JSON.
One alternate solution, which avoids having to persist the actual connection information is to basically create your own connection pool. This will require a singleton-scoped class with a ConcurrentDictionary ivar and likely the use of SemaphoreSlim to lock during reads and writes of that dictionary so that you don't create and orphan connections. Then, you'd just need to assign the key to their particular connection in the dictionary client somehow, such as via Session or a cookie. This is actually a little more secure as well, as you're not persisting the database connection info past the initial post, but you might end up exhausting the available server connections if there's too many simultaneous users. Of course, that could potentially be an issue regardless. You'll also need some policy for eviction of connections. It's not the easiest setup.
Personally, I'd just stick with using Session on this one. It's secure enough, as long as you take the standard session hijacking prevention measures, and it's simple to implement. If you are building a SPA-style app, then I'd stick with local storage, as that's going to be imminently better keeping the info client-side to begin with, but it requires a bit more plumbing that way.

variable set null after method

I'm building a web site, and I need to show a list of customers. When a customer is selected, to show his items, I send the id of the customer from the view with this:
<th>
#using (Html.BeginForm("SetID", "Client", FormMethod.Post, new
{ id = item.id.ToString() }))
{
#Html.Hidden("id", item.id.ToString());
<input type="submit" value="see items" />
}
</th>
I receive the id in the controller and save it to make the query and show the values this way.
private string customer_id
[HttpPost]
public ActionResult SetCustomer(string id) {
Save(id);
return RedirectToAction("Index");
}
private void Save(string id) {
this.customer_id = id;
}
But when I get redirected to the Index view, the variable "customer_id", is null. Is there something I'm missing?
Because you're not persisting the value anywhere.
HTTP is stateless. What this means in ASP.NET is that each HTTP requests results in a new instance of the controller being requested. So the following sequence of events is happening here:
User makes a request to SetCustomer, creating a new instance of the class
Value is stored in a class-level variable
Request is responded to and completed, the instance of the class is destroyed
User makes a request to Index, creating a new instance of the class
Since it's a new instance, no value is set. There are a variety of places you can store data, it just has to be in a context that both requests can access. Examples, in no particular order, include:
Database
Session
URL query string
Cookie
etc.
Basically, you have to write the value to some location which persists between requests. In-memory variables don't do that in web applications.
A simple example here could be to include the value on the query string in the redirect. In ASP.NET MVC, that might look something like this:
return RedirectToAction("Index", new { customer_id = id });
What this would do is include on a URL parameter a customer_id value when the user is redirected. So your Index action you could accept that parameter:
ActionResult Index(int? customer_id = null)
{
// use the customer id if one is provided
}
In this case I assumed that the value should be nullable in case the Index is ever requested without a value. But what you prefer to do for that is up to you. Basically this action now has an optional parameter, which you would use however you're currently trying to use it.
The benefit of this is that it maintains the intended statelessness of web applications. You're storing the state (the customer_id value) in the request/response itself, as opposed to some other medium (session, database, etc.) where you become responsible to maintaining it.
ASP.NET MVC controllers are instantiated to serve every request. Your local variable this.customer_id is not supposed to survive a call to the server. If you want to save something, it should go in a database table, or a file or somewhere persistent.
You could also store it in memory like in a cache, but that would need to be in a reference to something that lives longer than the controller (which will be thrown away after the server responds back to the browser).
If you want something like I described to be long lived, you might need to use a service to inject into your controllers. Many people would use a DI or IOC framework and life cycle configurations to accomplish this.

Cannot get variable I assigned to HttpContext.User

I am creating a basic authentication system with MVC 4 that uses custom logic. I have a UserModel class (which inherits from IPrincipal) that stores data I need to be persistent. To do this I am using the following code in my Controller:
if (ModelState.IsValid)
{
if (userModel.IsValidUser())
{
FormsAuthentication.SetAuthCookie(userModel.Username, false);
HttpContext.User = userModel;
// User is now logged in; send them to Index method to load MyeMan data
return RedirectToAction("Index", "Login");
}
}
Then, in the Index action:
if (IsUserLoggedIn())
{
UserModel userModel = (UserModel) HttpContext.User; // This line throws error
}
The error I get is:
Unable to cast object of type 'System.Web.Security.RolePrincipal' to
type 'MyProj.UserModel'.
When I look in debug, the HttpContext.User accepts the UserModel without complaint. Only when it redirects to the different action does its datatype change.
Am I doing something wrong or is this the complete wrong way to go about storing UserModel persisently without Sessions? Sessions will expire independently of the AuthCookie; I was told HttpContext.User is the way to go.
Assigning the user will work, but this assignment will not persist between requests. You have to make sure to set up the user at the beginning of each request, perhaps in a custom AuthorizeAttribute or IHttpModule. For example, you might have logic like:
Retrieve the relevant cookie from the request
Verify that the cookie corresponds to a valid session (e. g. by querying a database containing this information)
Retrieve the session information based on the cookie and store it in the User property
Also, when you assign HttpContext.Current.User consider assigning Thread.CurrentPrincipal as well.
Read Passing Data in an ASP.NET MVC Application
You can use TempData to pass the data between the action. It will be available for only subsequent requests
TempData["User"] = userModel;
// User is now logged in; send them to Index method to load MyeMan data
return RedirectToAction("Index", "Login");
In Index
UserModel user= (UserModel)TempData["User"];

ASP MVC4 + NHibernate objects in Session

I need to save a hibernate object into session and then retrieve one of it's foreign key properties like this:
public ActionResult Login(LoginModel model, string returnUrl) {
User usr = _userRepository.GetById(Convert.ToInt32(ModelState["User"].Value.AttemptedValue));
Session["user"] = usr;
}
public ActionResult Index() {
Customer customerActive = Session["user"].Customer.Active;
// this line throws an error:
// Initializing[Myproj.Models.Customer#3]-Could not initialize proxy - no Session.
}
As User.Customer is a foreign key and NHIbernate lazy loads it, the call fails. How could I prevent this "No session" failure?
If you want to continue with existing approach you would want to make sure that Customer is initialized before it was put into the session, e.g.
var userId = Convert.ToInt32(ModelState["User"].Value.AttemptedValue);
User usr = _userRepository.GetById(userId);
NHibernateUtil.Initialize(usr.Customer);
Session["user"] = usr;
but...
as commentators have hinted there are probably various better approaches as the session is not a great place to store what might become large and complex objects which have to be serialized and stored remotely if you are in a web farm.
If passing the userId around and loading from the database each time is a performance hit for you there are several things you can do, e.g.
You could put some caching in front of the database call
Store some basic user data within a cookie (or local storage) to save any db hit
-

MVC Routes - How to get a URL?

In my current project we have a notification system. When an oject is added to another objects collection, an email is sent to those who are subscibed to the parent object. This happens on the object layer and not in the View or Controller.
Here's the problem:
Although we can say who created what with what information in the email, we cannot embed links to those objects in the email because in the object layer there is no access to a UrlHelper. To construct a UrlHelper you need a RequestContext, which again does not exist on the object layer.
Question:
I want to make a helper class to create the url's for me. How can I create an object that will generate these urls without a request context? Is it possible?
The problem is compounded by the fact that you don't want a relative URL in an email, you want an absolute email so you need to hard-code the domain too because there is no request to grab it from.
Another factor is that emails can outlive the current site structure by months or years so you need a kind of permalink, and thus a way to associate multiple Urls with a single action (additional routes). This latter issue is also a factor in SEO where you don't want to leave any page behind.
For now a static method on your controller UrlToActionX(params) sitting next to the method ActionX seems like the simplest workaround. All it does is the appropriate string.Format(...) on the id's of the strongly-typed parameters to generate the permanent Url. Add a static domain on the front, or a domain from the user object (since you know which domain they visit when they come to your site) and you have your email link.
It's not ideal but at least you now have only one place to maintain the Url generation.
IMHO: When it comes to permanent links to a changing web site sometimes it's better to rely on "configuration over convention". :-)
I'm not aware of a way to do this, you MUST have access to the routes at the very least to make your own helper. Unless your business objects know about the registered routes, you can't get away from doing some hard-coding.
Here is how you might limit the hard-coding of urls though...
Code in a url with all the relevant bits in your object's methods..
class Event
{
public void SendEmail()
{
var url = string.Format("http://myurl.com/r/Event?eventId={0}", EventId);
//send emails...
}
}
Note the /r/Event piece of the url. This would be a map to a RController that would be responsible for taking arbitrary, made-up links and sending a 301 Permanent Redirect and going through the route engine to create a real url using the current routes. This way you are only hard-coding a utility controller url and not to the ever evolving controller actions of your real pages.
class RController : Controller
{
public ActionResult Event(int eventId)
{
Response.StatusCode = (int)HttpStatusCode.MovedPermanently;
Response.RedirectLocation = Url.Action("Details", "Event", new { eventId = eventId });
return null;
}
public ActionResult Register(int eventId)
{
Response.StatusCode = (int)HttpStatusCode.MovedPermanently;
Response.RedirectLocation = Url.Action("Register", "Event", new { eventId = eventId });
return null;
}
}
It just feels a bit better than hard-coding a bunch of different controllers/actions that you might decide to rename later. Think of it as your own little TinyUrl like service.
You could define an interface with a method that takes whatever information is necessary to create a URL (object ids or whatever) and returns a URL. Write an implementation of that interface that uses the UrlHelper to do this work, and then supply this to your object layer (ideally with an IoC container).
You could use:
VirtualPathUtility.ToAbsolute(string.Format("~/r/Event?eventId={0}", id))
to resolve the url. Still not nice though.

Categories

Resources