Search code examples
c#asp.net-mvcparameter-passing

Pro's & cons to pass data in a project in asp.net MVC


So I'm wondering, what are the pro's & cons of the various ways to pass data between pages in your project.

I know of:

  1. Sessions: I can't use this because my project needs to be deployed on something like Azure, sessions aren't good for multi-server deployment.
  2. Passing parameters between the various actionresults: This works good, but it can be very tedious to do this...
  3. Cookies: I was planning to use this for my project, but I have read that this isn't the best practice?

So I'm wondering what technique you guys are using (and why), so I can make a decision on what technique I will use.

For example: my user is logged in and for several ActionResults I need the UserId to access the userRepository, what is the best way to do this. Or maybe there is even a good way to hold the user as an object (then I wouldn't have to acces the db all the time)? I have set up a login system and its working fine, but doesn't the user get stored somewhere? Or does only some data of the user gets stored? I'm using this for instance:

FormsAuthentication.SetAuthCookie(user.Email, false);

Thanks in advance!


Solution

  • Passing usernames around sounds a lot like authentication. Take a look at ASP Membership https://msdn.microsoft.com/en-us/library/yh26yfzy(v=vs.140).aspx

    Depending on your requirements you could also look at TempData although this is only really useful for redirecting between actions. Using Tempdata in ASP.NET MVC - Best practice

    Edit - based on the fact you are using authorization cookies, you should consider MVC authorized attributes https://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute%28v=vs.118%29.aspx

    Or another good approach is to use a Base controller class that handles your authorization

     public BaseController: Controller
     {
           protected string username ;
    
           protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
               // Do authorization here
              username = // code to get username 
       {
     }