Как я могу исправить эту ошибку: «IFeatureCollection был удален. в Asp.net Основной Mvc

#c# #asp.net-core #.net-core #model-view-controller

Вопрос:

Как я могу исправить эту ошибку: «IFeatureCollection был удален. в Asp.net Основной Mvc

Я использовал Наблюдатель файловой системы для получения данных о событиях файлов в пути все работает нормально, и я отправил трассировку в базу данных, но идентификатор администратора и идентификатор роли, которые являются значениями сеанса, вызвали эту проблему, когда я попытался использовать их в методе OnChanged

это мой контроллер :

  **public IActionResult RHManager()
        {
            ViewBag.Idadmin = int.Parse(HttpContext.Session.GetInt32("id").ToString());
            ViewBag.RoleCreateur = int.Parse(HttpContext.Session.GetInt32("role_id").ToString());
            var Idadmin = int.Parse(HttpContext.Session.GetInt32("id").ToString());



            FileSystemWatcher watcher = new FileSystemWatcher();

            //Mention the Path that you want to monitor file events.

            watcher.Path = @"\100.100.1.6drh-m$";
            watcher.IncludeSubdirectories = true;
            watcher.NotifyFilter = NotifyFilters.Attributes |
            NotifyFilters.CreationTime |
            NotifyFilters.DirectoryName |
            NotifyFilters.FileName |
            NotifyFilters.LastAccess |
            NotifyFilters.LastWrite |
            NotifyFilters.Security |
            NotifyFilters.Size;
            watcher.Filter = "*.*";
            //File System Events to listen them
            watcher.Changed  = new FileSystemEventHandler(OnChanged);
            watcher.Created  = new FileSystemEventHandler(OnChanged);
            watcher.Deleted  = new FileSystemEventHandler(OnChanged);

            // Starting monitoring the folder.
            watcher.EnableRaisingEvents = true;

            return View(watcher);
        }


       

         void OnChanged(object source, FileSystemEventArgs e)
        {
            TraceFileManager trace = new TraceFileManager();
            trace.Time = DateTime.Now;
            trace.Adminid = int.Parse(HttpContext.Session.GetInt32("id").ToString());
            trace.Roleid = int.Parse(HttpContext.Session.GetInt32("id").ToString());
            trace.Changedfile = e.Name;
            trace.Seen = false;
            trace.Etat = "En attente";
            trace.Changetype = e.ChangeType.ToString();
            _context.Add(trace);
            
            _context.SaveChangesAsync();
        }**
 

Ответ №1:

Услуги с областью действия удаляются в конце запроса. Основная проблема заключается OnChanged в том, что запрос может быть вызван после завершения запроса. Когда вам нужна служба с областью действия за пределами запроса, вам нужно ввести IServiceScopeFactory и использовать ее для получения службы.

Idem, когда ControllerBase.HttpContext вызывается свойство OnChanged . Но невозможно получить HttpContext вне запроса. Затем вам нужна информация geed из HttpContext в запросе и установите в OnChanged вызове.

 public RhController : ControllerBase
{
    private IServiceScopeFactory _serviceScopeFactory;

    public RhController(IServiceScopeFactory serviceScopeFactory)
    {
        _serviceScopeFactory = serviceScopeFactory;
    }

    public IActionResult RHManager()
    {
        ViewBag.Idadmin = int.Parse(HttpContext.Session.GetInt32("id").ToString());
        ViewBag.RoleCreateur = int.Parse(HttpContext.Session.GetInt32("role_id").ToString());
        var Idadmin = int.Parse(HttpContext.Session.GetInt32("id").ToString());
        var IdRole = int.Parse(HttpContext.Session.GetInt32("id").ToString());


        FileSystemWatcher watcher = new FileSystemWatcher();
        ...
        //File System Events to listen them
        var fileSystemEventHandler = new FileSystemEventHandler((o, e) => OnChanged(e, Idadmin, IdRole));
        watcher.Changed  = fileSystemEventHandler;
        watcher.Created  = fileSystemEventHandler;
        watcher.Deleted  = fileSystemEventHandler;

        // Starting monitoring the folder.
        watcher.EnableRaisingEvents = true;

        return View(watcher);
    }

    void OnChanged(FileSystemEventArgs e, int admin, int role)
    {
        using (var scope = serviceScopeFactory.CreateScope())
        {
            var context = scope.ServiceProvider.GetService<RhContext>();

            TraceFileManager trace = new TraceFileManager();
            trace.Adminid = admin;
            trace.Roleid = role;
            ...

            context.Add(trace);
            context.SaveChangesAsync();
        }
    }
}
 

Комментарии:

1. Я скучаю по тому, что HttpContext вызывается из OnChanged…. Я отредактировал свой ответ.

Ответ №2:

Я пробую ваше решение, но проблемы сохраняются

полный код контроллера приведен ниже :

 using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using RoleBasedAuthorization.Models;
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;

namespace RoleBasedAuthorization.Controllers
{
    public class FileManagerController : Controller
    {

        ENAPORTALContext _context = new ENAPORTALContext();
        private readonly IServiceScopeFactory _serviceScopeFactory;

        public FileManagerController(IServiceScopeFactory serviceScopeFactory)
        {
            _serviceScopeFactory = serviceScopeFactory;
        }
        public IActionResult PQManager()
        {
            ViewBag.Idadmin = int.Parse(HttpContext.Session.GetInt32("id").ToString());
            return View();
        }
        public IActionResult FormulairesFManager()
        {
            ViewBag.Idadmin = int.Parse(HttpContext.Session.GetInt32("id").ToString());
            return View();
        }
        public IActionResult DGManager()
        {
            ViewBag.Idadmin = int.Parse(HttpContext.Session.GetInt32("id").ToString());
            return View();
        }
        public IActionResult DAFManager()
        {
            ViewBag.Idadmin = int.Parse(HttpContext.Session.GetInt32("id").ToString());
            ViewBag.RoleCreateur = int.Parse(HttpContext.Session.GetInt32("role_id").ToString());
            return View();
        }
        public IActionResult DAPManager()
        {
            ViewBag.Idadmin = int.Parse(HttpContext.Session.GetInt32("id").ToString());
            ViewBag.RoleCreateur = int.Parse(HttpContext.Session.GetInt32("role_id").ToString());
            return View();
        }
        public IActionResult DPCManager()
        {
            ViewBag.Idadmin = int.Parse(HttpContext.Session.GetInt32("id").ToString());
            ViewBag.RoleCreateur = int.Parse(HttpContext.Session.GetInt32("role_id").ToString());
            return View();
        }
        public IActionResult DMVManager()
        {
            ViewBag.Idadmin = int.Parse(HttpContext.Session.GetInt32("id").ToString());
            ViewBag.RoleCreateur = int.Parse(HttpContext.Session.GetInt32("role_id").ToString());
            return View();
        }
        public IActionResult PublicManager()
        {
            ViewBag.Idadmin = int.Parse(HttpContext.Session.GetInt32("id").ToString());
            return View();
        }
        public IActionResult DTManager()
        {
            ViewBag.Idadmin = int.Parse(HttpContext.Session.GetInt32("id").ToString());
            ViewBag.RoleCreateur = int.Parse(HttpContext.Session.GetInt32("role_id").ToString());
            return View();
        }
        public IActionResult DTPManager()
        {
            ViewBag.Idadmin = int.Parse(HttpContext.Session.GetInt32("id").ToString());
            ViewBag.RoleCreateur = int.Parse(HttpContext.Session.GetInt32("role_id").ToString());
            return View();
        }
        public IActionResult DTTManager()
        {
            ViewBag.Idadmin = int.Parse(HttpContext.Session.GetInt32("id").ToString());
            ViewBag.RoleCreateur = int.Parse(HttpContext.Session.GetInt32("role_id").ToString());
            return View();
        }
        public IActionResult SMQManager()
        {
            ViewBag.Idadmin = int.Parse(HttpContext.Session.GetInt32("id").ToString());
            ViewBag.RoleCreateur = int.Parse(HttpContext.Session.GetInt32("role_id").ToString());
            return View();
        }
        public IActionResult BoiteIdees()
        {
            ViewBag.Idadmin = int.Parse(HttpContext.Session.GetInt32("id").ToString());
            ViewBag.RoleCreateur = int.Parse(HttpContext.Session.GetInt32("role_id").ToString());

            return View();
        }

      


        public IActionResult Documentation()
        {
            ViewBag.Idadmin = int.Parse(HttpContext.Session.GetInt32("id").ToString());
            ViewBag.RoleCreateur = int.Parse(HttpContext.Session.GetInt32("role_id").ToString());
            return View();
        }
        public IActionResult DFManager()
        {
            ViewBag.Idadmin = int.Parse(HttpContext.Session.GetInt32("id").ToString());
            ViewBag.RoleCreateur = int.Parse(HttpContext.Session.GetInt32("role_id").ToString());
            return View();
        }
        /*     FILE MANAGER DRH*/


























        public IActionResult RHManager()
        {
            ViewBag.Idadmin = int.Parse(HttpContext.Session.GetInt32("id").ToString());
            ViewBag.RoleCreateur = int.Parse(HttpContext.Session.GetInt32("role_id").ToString());
            var Idadmin = int.Parse(HttpContext.Session.GetInt32("id").ToString());



            FileSystemWatcher watcher = new FileSystemWatcher();

            //Mention the Path that you want to monitor file events.

            watcher.Path = @"\100.100.1.6drh-m$";
            watcher.IncludeSubdirectories = true;
            watcher.NotifyFilter = NotifyFilters.Attributes |
            NotifyFilters.CreationTime |
            NotifyFilters.DirectoryName |
            NotifyFilters.FileName |
            NotifyFilters.LastAccess |
            NotifyFilters.LastWrite |
            NotifyFilters.Security |
            NotifyFilters.Size;
            watcher.Filter = "*.*";
            //File System Events to listen them
            watcher.Changed  = new FileSystemEventHandler(OnChanged);
            watcher.Created  = new FileSystemEventHandler(OnChanged);
            watcher.Deleted  = new FileSystemEventHandler(OnChanged);

            // Starting monitoring the folder.
            watcher.EnableRaisingEvents = true;

            return View(watcher);
        }


       

         void OnChanged(object source, FileSystemEventArgs e)
        {
            using (var scope = _serviceScopeFactory.CreateScope())
            {
                var context = scope.ServiceProvider.GetService<ENAPORTALContext>();
                var Idadmin = int.Parse(HttpContext.Session.GetInt32("id").ToString());     /*Admin ID variable session will be inserted into db               error : IFeatureCollection has been disposed.*/
                var RoleCreateur = int.Parse(HttpContext.Session.GetInt32("role_id").ToString()); /*role ID variable session will be inserted into db*/
                TraceFileManager trace = new TraceFileManager();
                trace.Time = DateTime.Now;
                trace.Adminid = Idadmin;
                trace.Roleid = RoleCreateur;
                trace.Changedfile = e.Name;
                trace.Seen = false;
                trace.Etat = "En attente";
                trace.Changetype = e.ChangeType.ToString();
                _context.Add(trace);

                _context.SaveChangesAsync();
            }
        }


    










    }
}
 

Комментарии:

1. Лучше всего отредактировать вопрос, чтобы включить дополнительную информацию, такую как повторная попытка.

2. Если мой ответ ответит на ваш вопрос, можете ли вы принять его?