简体   繁体   English

System.IO.FileNotFoundException:无法加载指定的文件。 文件名:“ System.Net.Sockets.resources”

[英]System.IO.FileNotFoundException: Could not load the specified file. File name: 'System.Net.Sockets.resources'

I am developing a dotnet core application with Angular. 我正在用Angular开发一个dotnet核心应用程序。

I am trying to migrate to dotnet core 2.1 and Angular 6. 我正在尝试迁移到dotnet core 2.1和Angular 6。

I was able to migrate first to dotnet core 2.1 with no problems, but when I tried to migrate to the latest Angular build I encountered problems. 我能够首先毫无问题地迁移到dotnet core 2.1,但是当我尝试迁移到最新的Angular构建时,遇到了问题。

It is not the problem with Angular itself, but with webpack. Angular本身不是问题,而是webpack。 I upgraded all the packages in package.json (with the exception of webpack ones) to the latest versions with no problem, but HMR was not working and I was not able to run 我将package.json中的所有软件包(webpack除外)都毫无问题地升级到了最新版本,但是HMR无法正常工作,并且我无法运行

webpack --config webpack.config.vendor.js

either. 无论是。

So, I used 所以,我用

npm install npm-check-updates -g
ncu -u
npm install

to upgrade webpack also. 也可以升级webpack。

I now have this package.json: 我现在有这个package.json:

{
  "name": "SIGAD",
  "private": true,
  "version": "0.0.0",
  "scripts": {
    "start": "node --max-old-space-size=1600 app.js < /dev/null",
    "test": "karma start ClientApp/test/karma.conf.js"
  },
  "dependencies": {
    "@angular-cool/storage": "^1.0.1",
    "@angular/animations": "^6.1.7",
    "@angular/common": "^6.1.7",
    "@angular/compiler": "^6.1.7",
    "@angular/core": "^6.1.7",
    "@angular/forms": "^6.1.7",
    "@angular/http": "^6.1.7",
    "@angular/platform-browser": "^6.1.7",
    "@angular/platform-browser-dynamic": "^6.1.7",
    "@angular/platform-server": "^6.1.7",
    "@angular/router": "^6.1.7",
    "@ng-idle/core": "^6.0.0-beta.3",
    "@ng-idle/keepalive": "^6.0.0-beta.3",
    "@ngx-translate/core": "^10.0.2",
    "@ngx-translate/http-loader": "^3.0.1",
    "@types/webpack-env": "^1.13.6",
    "angular2-cool-storage": "^3.1.3",
    "angular2-moment": "^1.9.0",
    "angular2-template-loader": "0.6.2",
    "aspnet-prerendering": "^3.0.1",
    "aspnet-webpack": "^3.0.0",
    "core-js": "^2.5.7",
    "es6-shim": "0.35.3",
    "isomorphic-fetch": "2.2.1",
    "json-loader": "0.5.7",
    "ng-pick-datetime": "^6.0.16",
    "ng2-datepicker-bootstrap": "^1.0.0",
    "raw-loader": "0.5.1",
    "rxjs": "^6.3.2",
    "rxjs-compat": "^6.3.2",
    "to-string-loader": "1.1.5",
    "webpack-hot-middleware": "^2.24.0",
    "webpack-merge": "^4.1.4",
    "zone.js": "^0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.8.1",
    "@angular/cdk": "^6.4.7",
    "@angular/cli": "^6.2.1",
    "@angular/compiler-cli": "^6.1.7",
    "@angular/language-service": "^6.1.7",
    "@angular/material": "^6.4.7",
    "@ngtools/webpack": "^6.2.1",
    "@types/chai": "4.1.5",
    "@types/jasmine": "^2.8.8",
    "@types/node": "^10.9.4",
    "awesome-typescript-loader": "^5.2.1",
    "bootstrap": "^4.1.3",
    "chai": "4.1.2",
    "codelyzer": "^4.4.4",
    "css": "^2.2.4",
    "css-loader": "^1.0.0",
    "event-source-polyfill": "0.0.16",
    "expose-loader": "^0.7.5",
    "extract-text-webpack-plugin": "^4.0.0-beta.0",
    "file-loader": "^2.0.0",
    "html-loader": "^0.5.5",
    "jasmine-core": "^3.2.1",
    "jasmine-spec-reporter": "^4.2.1",
    "jquery": "^3.3.1",
    "karma": "^3.0.0",
    "karma-chai": "0.1.0",
    "karma-chrome-launcher": "^2.2.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.1.2",
    "karma-jasmine-html-reporter": "^1.3.1",
    "karma-webpack": "3.0.5",
    "popper.js": "^1.14.4",
    "preboot": "^6.0.0-beta.5",
    "protractor": "^5.4.1",
    "reflect-metadata": "^0.1.12",
    "rxjs-tslint": "^0.1.5",
    "style-loader": "^0.23.0",
    "tslint": "^5.11.0",
    "typescript": "^3.0.3",
    "url-loader": "^1.1.1",
    "webpack": "^4.18.1",
    "webpack-cli": "^3.1.0"
  },
  "buildOptions": {
    "emitEntryPoint": true
  }
}

The problem is I get internal server error when I try to start my application. 问题是当我尝试启动应用程序时出现内部服务器错误。 With debug I catch this exception: 通过调试,我捕获到此异常:

System.IO.FileNotFoundException: Could not load the specified file.
File name: 'System.Net.Sockets.resources'
   at System.Runtime.Loader.AssemblyLoadContext.ResolveUsingEvent(AssemblyName assemblyName)

I did no changes to my C# code. 我没有对C#代码进行任何更改。 I upgraded all dependencies after I migrated to dotnet core 2.1 with no problem. 迁移到dotnet core 2.1之后,我没有问题就升级了所有依赖项。

My Startup.cs is: 我的Startup.cs是:

namespace SIGAD
{
    public class Startup
    {
        private static string databaseConnection = "";
        private const string SecretKey = "iNivDmHLpUA223sqsfhqGbMRdRj1PVkH"; // todo: get this from somewhere secure
        private readonly SymmetricSecurityKey _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));

        public Startup(IConfiguration config)
        {
            Configuration = config;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            try {

                services.AddAutoMapper();

                databaseConnection = Configuration.GetConnectionString("DefaultConnection");
                if (databaseConnection == null) databaseConnection = "Server=localhost\\SQLEXPRESS;Database=SIGADCORE;Trusted_Connection=true";

                services.AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(databaseConnection));

                DatabaseConnection.ConnectionString = databaseConnection;

                services.AddSingleton<IJwtFactory, JwtFactory>();

                services.AddIdentity<ApplicationUser, IdentityRole>()
                    .AddEntityFrameworkStores<ApplicationDbContext>()
                    .AddDefaultTokenProviders();

                // jwt wire up
                // Get options from app settings
                var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));

                // Configure JwtIssuerOptions
                services.Configure<JwtIssuerOptions>(options =>
                {
                    options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
                    options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
                    options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
                });

                services.AddAuthorization(options =>
                {
                    options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess));
                });

                // Add application services.
                services.AddTransient<IEmailSender, EmailSender>();
                services.AddNodeServices();

                services.AddSingleton(Configuration);

                services.Configure<CookiePolicyOptions>(options =>
                {
                    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                    options.CheckConsentNeeded = context => true;
                    options.MinimumSameSitePolicy = SameSiteMode.None;
                });

                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            }
            catch (Exception e)
            {
                AddErrorToDatabase(e);
            }
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider, ILoggerFactory loggerFactory)
        {
            try {

                loggerFactory.AddConsole(Configuration.GetSection("Logging"));
                loggerFactory.AddDebug();

                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();

                    app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                    {
                        HotModuleReplacement = true,
                        HotModuleReplacementEndpoint = "/dist/__webpack_hmr"
                    });
                }
                else
                {
                    app.UseExceptionHandler("/Error");
                    app.UseHsts();
                }

                app.UseDefaultFiles();
                app.UseHttpsRedirection();
                app.UseStaticFiles();
                app.UseCookiePolicy();

                var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));
                var tokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],

                    ValidateAudience = true,
                    ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = _signingKey,

                    RequireExpirationTime = false,
                    ValidateLifetime = false,
                    ClockSkew = TimeSpan.Zero
                };

                app.UseAuthentication();

                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");

                    routes.MapSpaFallbackRoute(
                        name: "spa-fallback",
                        defaults: new { controller = "Home", action = "Index" });
                });


                CreateRoles(serviceProvider);

                if (Thread.CurrentThread.CurrentUICulture.Name == "en-US")
                    SessionConstants.CultureInfo = CultureInfo.CreateSpecificCulture("ro-RO");
                else
                    SessionConstants.CultureInfo = CultureInfo.CreateSpecificCulture("ro-RO");

                Thread.CurrentThread.CurrentCulture = SessionConstants.CultureInfo;
                Thread.CurrentThread.CurrentUICulture = SessionConstants.CultureInfo;

            }
            catch (Exception e)
            {
                AddErrorToDatabase(e);
            }
        }

        private void CreateRoles(IServiceProvider serviceProvider)
        {

            var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
            var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
            Task<IdentityResult> roleResult;

            string[] roleNames = { RoleNames.Admin, RoleNames.Supraveghetor, RoleNames.Operator, RoleNames.OperatorCuModificare, RoleNames.OperatorCuVizualizare };

            //Check that there is an Administrator role and create if not

            foreach (var roleName in roleNames)
            {
                Task<bool> hasAdminRole = roleManager.RoleExistsAsync(roleName);
                hasAdminRole.Wait();
                if (!hasAdminRole.Result)
                {
                    roleResult = roleManager.CreateAsync(new IdentityRole(roleName));
                    roleResult.Wait();
                }
            }

        }

        public static void AddErrorToDatabase(Exception e)
        {
            // Get stack trace for the exception with source file information
            var st = new StackTrace(e, true);
            // Get the stack frames

            string file = "";
            string fileTemp = "";
            string method = "";
            string lineNumber = "";

            foreach (StackFrame frame in st.GetFrames())
            {
                // Get the file name from the stack frame
                fileTemp = frame.GetFileName() ?? "";
                fileTemp = fileTemp.Replace('\\', '-').Split('-').Last().Trim();

                int line = frame.GetFileLineNumber();

                if (line > 0)
                {
                    file += "-> " + fileTemp + "\n";

                    // Get the method from the stack frame
                    method = "-> " + frame.GetMethod().ToString().Substring(frame.GetMethod().ToString().IndexOf(' '), frame.GetMethod().ToString().IndexOf('(') - frame.GetMethod().ToString().IndexOf(' ')) + "\n";

                    // Get the line number from the stack frame
                    lineNumber += "-> " + frame.GetFileLineNumber().ToString() + "\n";
                }
            }

            string destails = e.Message;

            if (e.InnerException != null)
            {
                var innerException = e;

                Exception realerror = e;
                while (realerror.InnerException != null)
                {
                    realerror = realerror.InnerException;
                    destails += "\n" + realerror.Message;
                }
            }

            if (databaseConnection != null)
            {
                string QueryString = "INSERT INTO Error(Description,Moment,[File],Method,Line) VALUES (@description,@moment,@file,@method,@line)";

                System.Type tipProdus = e.GetType();

                SqlConnection myConnection = new SqlConnection(databaseConnection);
                SqlDataAdapter myCommand = new SqlDataAdapter(QueryString, myConnection);
                DataSet ds = new DataSet();

                // add the elements to the list
                using (SqlConnection con = new SqlConnection(databaseConnection))
                {
                    con.Open();
                    using (SqlCommand cmd = new SqlCommand(QueryString, con))
                    {
                        cmd.Parameters.AddWithValue("@description", destails);
                        cmd.Parameters.AddWithValue("@moment", DateTime.Now);
                        cmd.Parameters.AddWithValue("@file", file);
                        cmd.Parameters.AddWithValue("@method", method);
                        cmd.Parameters.AddWithValue("@line", lineNumber);
                        cmd.ExecuteNonQuery();
                    }
                    con.Close();
                }

            }
            else
            {
                //string folderPath = System.IO.Directory.GetCurrentDirectory();
                string path = "errors" + DateTime.Now.ToString("ddMMyyyyhhmmss") + ".txt";
                if (!File.Exists(path))
                {
                    // Create a file to write to.
                    using (StreamWriter sw = File.CreateText(path))
                    {
                        sw.WriteLine(destails);
                        sw.WriteLine(DateTime.Now);
                        sw.WriteLine(file);
                        sw.WriteLine(method);
                        sw.WriteLine(lineNumber);
                    }
                }
            }
        }

    }
}

There was no error, but the changes where not being reflected in the app. 没有错误,但更改未反映在应用程序中。 I tried running 我尝试跑步

webpack --config webpack.config.vendor.js

but now I was getting the error 但是现在我得到了错误

ERROR in ./node_modules/bootstrap/dist/js/bootstrap.js
Module not found: Error: Can't resolve 'popper.js' in 'C:\Users\Andrei\Desktop\Bosch.SIGAD-Core\SIGAD\node_modules\bootstrap\dist\js'

so I installed it with 所以我用

npm install popper.js -D

ran

webpack --config webpack.config.vendor.js

again and it worked, but now I am getting this error. 再次,它的工作,但现在我收到此错误。

I don't even know where to start investigating this error. 我什至不知道从哪里开始调查此错误。 Any ideas would be great. 任何想法都很棒。

Thank you! 谢谢!

UPDATE: 更新:

if I commnet: 如果我进行通讯:

 app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
    {
       HotModuleReplacement = true,
        HotModuleReplacementEndpoint = "/dist/__webpack_hmr"
 });

in Startup.cs, I don't get internal server error, but I get 在Startup.cs中,我没有收到内部服务器错误,但得到了

Uncaught Error: Type e is part of the declarations of 2 modules: e and e! Please consider moving e to a higher module that imports e and e. You can also create a new NgModule that exports and includes e then import that NgModule in e and e.

in browser console... 在浏览器控制台中...

UPDATE 2: 更新2:

I want to emphasize that even if I create a new project with dotnet core and Angular, after I 我想强调的是,即使我使用dotnet core和Angular创建一个新项目,

npm install npm-check-updates -g ncu -u npm install

I get this error and I am not able to start my app 我收到此错误,但无法启动我的应用

I have found this: 我发现了这一点:

https://github.com/dotnet/coreclr/issues/14482 https://github.com/dotnet/coreclr/issues/14482

which seems to be the escat same problem, but I do not see any solution there. 这似乎是escat的同样问题,但我在那儿看不到任何解决方案。

steps to have an aplication using .NET Core 2.1 API and Angular 6 .NET Core 2.1 API和Angular 6进行复制的步骤

1.-create a new proyect Aplication web ASP.NET Core -->choose Angular https enabled 1.-创建一个新的Proyect Aplication Web ASP.NET Core->选择启用Angular https

2.-close the project 2.-关闭项目

3.-make a copy ClientApp src to another folder 3.-将ClientApp src复制到另一个文件夹

4.-remove ClientApp folder 4.删除ClientApp文件夹

5.-in folder of the app (where is startup.cs) write 在应用程序的5.-in文件夹中(在startup.cs中)写入

ng new ClientApp

see my version is Angular CLI:6.1.3 Node 10.5.0 OS:win32 x64 看到我的版本是Angular CLI:6.1.3 Node 10.5.0 OS:win32 x64

6.-Open the project and ejecute in IISExpress (ask you about the https, don't worry add security exception of your navigator) 6.-打开项目并在IISExpress中发布(询问您有关https的信息,不要担心添加导航器的安全性例外)

7.-You see in localhost:##### the aplication 7.-您在localhost:#####中看到了应用

8.-Copy the folder src saved before 8.-复制之前保存的文件夹src

9.-Goto to ClientApp folder and add bootstrap-css only 9.-转到ClientApp文件夹并仅添加bootstrap-css

 npm install bootstrap-css-only

10.-in angular.json, you must include the .css in "styles" so your angular.json becomes like 10.-在angular.json中,必须在“样式”中包含.css,以便您的angular.json像

 ...
             "styles": [
              "src/styles.css",
              "node_modules/bootstrap-css-only/css/bootstrap.css"
            ],
...

11.-You can instal if you want ng-bootstrap (in ClientApp folder) 11.-如果需要ng-bootstrap,可以安装(在ClientApp文件夹中)

npm install --save @ng-bootstrap/ng-bootstrap

And in app.module.ts add the import 并在app.module.ts中添加导入

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

and add NgbModule, in imports like show it in https://ng-bootstrap.github.io/#/getting-started 并在导入中添加NgbModule,例如在https://ng-bootstrap.github.io/#/getting-started中显示

12.-Finally replace nav-manu.component.html with the code 12.最后用代码替换nav-manu.component.html

<ul class="nav flex-column">
  <li class="nav-item" [routerLinkActive]='["link-active"]' [routerLinkActiveOptions]='{ exact: true }'>
    <a class="nav-link" [routerLink]='["/"]'>Home</a>
  </li>
  <li class="nav-item" [routerLinkActive]='["link-active"]' >
    <a class="nav-link" [routerLink]='["/counter"]' >Counter</a>
  </li>
  <li class="nav-item" [routerLinkActive]='["link-active"]' >
    <a class="nav-link" [routerLink]='["/fetch-data"]' >Fech Data</a>
  </li>
</ul>

Yet we have an API aplication using angular 6 但是我们有一个使用角度6的API应用程序

see in https://github.com/EliseoPlunker/sample-.NET-Core-2.1-Angular-6 参见https://github.com/EliseoPlunker/sample-.NET-Core-2.1-Angular-6

The error had nothing to do with C# 该错误与C#无关

It was an Angular problem. 这是一个角度问题。

For some reason, Angular didn't told anything about some compilation errors. 出于某种原因,Angular没有告知任何有关编译错误的信息。 Visual Studio didn't show any errors and there were no errors in the browser's console and there were no errors in Output -> ASP.NET Core Web server (though sometimes they appear). Visual Studio没有显示任何错误,浏览器的控制台中没有错误,并且Output-> ASP.NET Core Web服务器中也没有错误(尽管有时会出现)。

I took Eliseo's advice to create the project from scratch and actually adding one element at a time. 我接受了Eliseo的建议,从头开始创建项目,并实际上一次添加了一个元素。 There was no indication of this, but in some services, there was this import: 没有迹象表明这一点,但是在某些服务中,存在此导入:

import 'rxjs/add/operator/map';

I know that map is not used anymore, but I think that this should be shown as an error in the compilation. 我知道不再使用map,但是我认为应该在编译中将其显示为错误。

After removing this error and others, it worked. 删除此错误和其他错误后,它开始工作。

I believed it was a C# because it was the only indication of an error that I got. 我认为这是C#,因为它是我收到的错误的唯一指示。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 奇怪的错误:System.IO.FileNotFoundException:无法加载文件或程序集 - Weird Error: System.IO.FileNotFoundException: Could not load file or assembly System.IO.FileNotFoundException: 无法加载文件或程序集 C# - System.IO.FileNotFoundException: Could not load file or assembly C# System.IO.FileNotFoundException:无法加载文件或程序集&#39;System.Net.Security,Version = 4.0.0.0 - System.IO.FileNotFoundException: Could not load file or assembly 'System.Net.Security, Version=4.0.0.0 Google Api-System.IO.FileNotFoundException:无法加载文件或程序集“ System.Net.Http.Primitives” - Google Api - System.IO.FileNotFoundException : Could not load file or assembly 'System.Net.Http.Primitives' 无法加载文件或程序集System.IO.FileNotFoundException - Could not load file or assembly System.IO.FileNotFoundException System.IO.FileNotFoundException:无法加载文件或程序集 - System.IO.FileNotFoundException: Could not load file or assembly System.IO.FileNotFoundException: '无法加载文件或程序集 - System.IO.FileNotFoundException: 'Could not load file or assembly System.IO.FileNotFoundException:找不到文件 - System.IO.FileNotFoundException : Could not find file .NET 6 System.IO.FileNotFoundException:无法加载文件或程序集 System.Linq,版本 = 6.0.0.0 - .NET 6 System.IO.FileNotFoundException: Could not load file or assembly System.Linq, Version=6.0.0.0 .NET 7 System.IO.FileNotFoundException:找不到文件 - .NET 7 System.IO.FileNotFoundException: Could not find file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM