-1

I want to understand how does the static variable username retain its value across action invocations like Download/Upload in the following code. It is initialized once in FileOperations. Isn't the controller class instantiated every time an action is called?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Newtonsoft.Json;
using Syncfusion.EJ2.FileManager.Base;
using Newtonsoft.Json.Serialization;
using Syncfusion.EJ2.FileManager.PhysicalFileProvider;
using Microsoft.Extensions.Diagnostics.HealthChecks;

namespace FileManager.Controllers
{
    public class FileManagerDirectoryContent1
    {
        public Dictionary<string, object> CustomData { get; set; }
        public FileManagerDirectoryContent[] Data { get; set; }
        public bool ShowHiddenItems { get; set; }
        public string SearchString { get; set; }
        public bool CaseSensitive { get; set; }
        public IList<IFormFile> UploadFiles { get; set; }
        public string[] RenameFiles { get; set; }
        public string TargetPath { get; set; }
        public string ParentId { get; set; }
        public string FilterId { get; set; }
        public string FilterPath { get; set; }
        public string Id { get; set; }
        public string Type { get; set; }
        public bool IsFile { get; set; }
        public bool HasChild { get; set; }
        public DateTime DateCreated { get; set; }
        public DateTime DateModified { get; set; }
        public string PreviousName { get; set; }
        public long Size { get; set; }
        public string Name { get; set; }
        public string[] Names { get; set; }
        public string NewName { get; set; }
        public string Action { get; set; }
        public string Path { get; set; }
        public FileManagerDirectoryContent TargetData { get; set; }
        public AccessPermission Permission { get; set; }
    }
    [Route("api/[controller]")]
    public class HomeController : Controller
    {
        **public static string username;**
        public PhysicalFileProvider operation;
        public string basePath;
        public HomeController(IHostingEnvironment hostingEnvironment)
        {
            this.basePath = hostingEnvironment.ContentRootPath;
            this.operation = new PhysicalFileProvider();
         
        }
        [Route("FileOperations")]
        public object FileOperations([FromBody] FileManagerDirectoryContent1 args)
        {
            username = args.CustomData["User_name"].ToString();
            if(username == "Client1")
            {
                this.operation.RootFolder(this.basePath + "\\" + "wwwroot\\" + username);
            }
            if (args.Action == "delete" || args.Action == "rename")
            {
                if ((args.TargetPath == null) && (args.Path == ""))
                {
                    FileManagerResponse response = new FileManagerResponse();
                    response.Error = new ErrorDetails { Code = "401", Message = "Restricted to modify the root folder." };
                    return this.operation.ToCamelCase(response);
                }
            }
            switch (args.Action)
            {
                case "read":
                    // reads the file(s) or folder(s) from the given path.
                    return this.operation.ToCamelCase(this.operation.GetFiles(args.Path, args.ShowHiddenItems));
                     

                case "delete":
                    // deletes the selected file(s) or folder(s) from the given path.
                    return this.operation.ToCamelCase(this.operation.Delete(args.Path, args.Names));
                case "copy":
                    // copies the selected file(s) or folder(s) from a path and then pastes them into a given target path.
                    return this.operation.ToCamelCase(this.operation.Copy(args.Path, args.TargetPath, args.Names, args.RenameFiles, args.TargetData));
                case "move":
                    // cuts the selected file(s) or folder(s) from a path and then pastes them into a given target path.
                    return this.operation.ToCamelCase(this.operation.Move(args.Path, args.TargetPath, args.Names, args.RenameFiles, args.TargetData));
                case "details":
                    // gets the details of the selected file(s) or folder(s).
                    return this.operation.ToCamelCase(this.operation.Details(args.Path, args.Names, args.Data));
                case "create":
                    // creates a new folder in a given path.
                    return this.operation.ToCamelCase(this.operation.Create(args.Path, args.Name));
                case "search":
                    // gets the list of file(s) or folder(s) from a given path based on the searched key string.
                    return this.operation.ToCamelCase(this.operation.Search(args.Path, args.SearchString, args.ShowHiddenItems, args.CaseSensitive));
                case "rename":
                    // renames a file or folder.
                    return this.operation.ToCamelCase(this.operation.Rename(args.Path, args.Name, args.NewName));
            }
            return null;
        }

        // uploads the file(s) into a specified path
        [Route("Upload")]
        public IActionResult Upload(string path, IList<IFormFile> uploadFiles, string action)
        {
            if (username == "Client1")
            {
                this.operation.RootFolder(this.basePath + "\\" + "wwwroot\\" + username);
            }
            
            FileManagerResponse uploadResponse;
            uploadResponse = operation.Upload(path, uploadFiles, action, null);
            if (uploadResponse.Error != null)
            {
                Response.Clear();
                Response.ContentType = "application/json; charset=utf-8";
                Response.StatusCode = Convert.ToInt32(uploadResponse.Error.Code);
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = uploadResponse.Error.Message;
            }
            return Content("");
        }

        // downloads the selected file(s) and folder(s)
        [Route("Download")]
        public IActionResult Download(string downloadInput)
        {
            if (username == "Client1")
            {
                this.operation.RootFolder(this.basePath + "\\" + "wwwroot\\" + username);
            }
           
            FileManagerDirectoryContent args = JsonConvert.DeserializeObject<FileManagerDirectoryContent>(downloadInput);
            return operation.Download(args.Path, args.Names, args.Data);
        }

        // gets the image(s) from the given path
        [Route("GetImage")]
        public IActionResult GetImage(FileManagerDirectoryContent args)
        {
            if (username == "Client1")
            {
                this.operation.RootFolder(this.basePath + "\\" + "wwwroot\\" + username);
            }

            return this.operation.GetImage(args.Path, args.Id, false, null, null);
        }
        public IActionResult Index()
        {
            return View();
        }
     
    }
}
user3656651
  • 619
  • 1
  • 9
  • 25
  • 3
    This is [exactly what you'd expect to happen](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/static). And a terrifyingly bad idea. – Kevin Krumwiede May 31 '22 at 18:51
  • 4
    The controller class is instantiated every time there's a request. However, if you put a static field in your class, that's shared across all controller instances, and thus you're going to have very screwy behavior, especially if that static field contains a username. This is definitely something you should avoid. – mason May 31 '22 at 18:51
  • You should only use static variable for things that are global to the application, for example you might have a static 'Servername' variable, which does change for each request. A static 'Uername' is very bad, since the value will be the same for each request (the latest assigned value). – Poul Bak May 31 '22 at 19:26

1 Answers1

0

static properties can be shared with entire code of application and you will always receive same instance of class by default, when will you try to access static property

  • I guess this gives a bit more understanding: "The static member is callable on a class even when no instance of the class has been created." So that means the static variable lives across class instantiations in this case and kind of acts like a global variable that lives across instances. – user3656651 Jun 01 '22 at 00:55
  • not only in this case, it acts the same in every language/environment – Bartłomiej Stasiak Jun 01 '22 at 01:36