Iis 进程内托管在.NETCore2.2上减慢了API响应时间

Iis 进程内托管在.NETCore2.2上减慢了API响应时间,iis,asp.net-core,aspnetboilerplate,asp.net-core-2.2,Iis,Asp.net Core,Aspnetboilerplate,Asp.net Core 2.2,我最近将.NET核心web API从2.1升级到了2.2。微软声称,新的进程内托管模型应该比进程外托管模型更好 然而,当我在.csproj中将IIS托管模型设置为InProcess时,平均API响应比我设置OutOfProcess时高50-100ms。 知道为什么它会减慢API响应时间(更高的ping)吗 My Startup.cs: public class Startup { public Startup(IConfiguration configuration)

我最近将.NET核心web API从2.1升级到了2.2。微软声称,新的进程内托管模型应该比进程外托管模型更好

然而,当我在.csproj中将IIS托管模型设置为
InProcess
时,平均API响应比我设置
OutOfProcess
时高50-100ms。 知道为什么它会减慢API响应时间(更高的ping)吗

My Startup.cs:

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            IoCContainer.Configuration = configuration;
        }

        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)
        {
            //Add proper cookie request to follow GDPR
            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;
            });

            //Add SendGrid email sender
            services.AddSendGridEmailSender();

            //Add general email template sender
            services.AddEmailTemplateSender();

            //Add ExcelFileDownloadService
            services.AddTransient<IExcelFileDownloadService, ExcelFileDownloadService>();
            //Add ExcelFileUploadService
            services.AddTransient<IExcelFileUploadService, ExcelFileUploadService>();
            //Add FileUploadService
            services.AddTransient<IUploadFileService, UploadFileService>();

            //CORS
            services.AddCors();

            //Add ApplicationDbContext to DI using MSSQL
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(IoCContainer.Configuration.GetConnectionString("AspifyConnection")));

            //Store keys to File System
            string path = Directory.GetCurrentDirectory() + @"\keys\";
            services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(path));


            //Add RepositoryWrapper to DI
            services.AddScoped<IRepositoryWrapper, RepositoryWrapper>();

            //Adds cookie based authentication
            //Adds classes like UserManager, SignInManager, PasswordHashers etc.
            services.AddIdentity<ApplicationUser, ApplicationRole>()
                .AddUserManager<UserManager<ApplicationUser>>()
                //Adds UserStore and RoleStore from this context
                .AddEntityFrameworkStores<ApplicationDbContext>()
                //Adds a provider that generates unique keys and hashes
                .AddDefaultTokenProviders();


            //Add JWT authentication for API clients
            var key = Encoding.ASCII.GetBytes(IoCContainer.Configuration["JwtSecretKey"]);
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata = false;
                options.SaveToken = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Administrator"));
            });

            //Change Identity Framework password policy
            services.Configure<IdentityOptions>(options =>
            {
                options.Password.RequireDigit = false;
                options.Password.RequiredLength = 5;
                options.Password.RequireLowercase = true;
                options.Password.RequireUppercase = false;
                options.Password.RequireNonAlphanumeric = false;
            });

            services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");

            services.AddMvc(options =>
            {

            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
        {
            //Setup identity
            app.UseAuthentication();

            UpdateDatabase(app);

            //Allow all CORS
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());

            app.UseDeveloperExceptionPage();

            //Force non-essential cookies to only store if the user has consented
            app.UseCookiePolicy();

            //Enable static files in wwwroot folder
            app.UseStaticFiles();

            //set HTTP routes
            app.UseMvc(routes =>
            {

                //Api route
                routes.MapRoute(
                name: "api",
                template: "api/{controller}/{action}/{moreInfo?}");

                //Default route to React
                routes.MapRoute(
                    name: "default",
                    template: "{*path}",
                    defaults: new { controller = "Home", action = "Index" });
            });
        }

        private static void UpdateDatabase(IApplicationBuilder app)
        {
            using (var serviceScope = app.ApplicationServices
                .GetRequiredService<IServiceScopeFactory>()
                .CreateScope())
            {
                using (var context = serviceScope.ServiceProvider.GetService<ApplicationDbContext>())
                {
                    context.Database.EnsureCreated();
                }
            }
        }
    }
公共类启动
{
公共启动(IConfiguration配置)
{
IoCContainer.Configuration=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
//添加正确的cookie请求以遵循GDPR
配置(选项=>
{
//此lambda确定给定请求是否需要非必要cookie的用户同意。
options.checkApprovered=context=>true;
options.MinimumSameSitePolicy=SameSiteMode.None;
});
//添加SendGrid电子邮件发件人
services.AddSendGridEmailSender();
//添加常规电子邮件模板发件人
services.AddEmailTemplateSender();
//添加ExcelFileDownloadService
services.AddTransient();
//添加ExcelFileUploadService
services.AddTransient();
//添加文件上传服务
services.AddTransient();
//科尔斯
services.AddCors();
//使用MSSQL将ApplicationDbContext添加到DI
services.AddDbContext(选项=>
使用SQLServer(IoCContainer.Configuration.GetConnectionString(“AspifyConnection”));
//将密钥存储到文件系统
字符串路径=Directory.GetCurrentDirectory()++“\keys\”;
services.AddDataProtection().PersistKeyStoreFileSystem(新目录信息(路径));
//将RepositoryWrapper添加到DI
services.addScope();
//添加基于cookie的身份验证
//添加UserManager、SignInManager、PasswordHasher等类。
服务.额外性()
.AddUserManager()
//从此上下文中添加UserStore和RoleStore
.AddEntityFrameworkStores()
//添加生成唯一键和哈希的提供程序
.AddDefaultTokenProviders();
//为API客户端添加JWT身份验证
var key=Encoding.ASCII.GetBytes(IoCContainer.Configuration[“JwtSecretKey”]);
services.AddAuthentication(选项=>
{
options.DefaultAuthenticateScheme=JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme=JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(选项=>
{
options.RequireHttpsMetadata=false;
options.SaveToken=true;
options.TokenValidationParameters=新的TokenValidationParameters
{
ValidateSuersigningKey=true,
IssuerSigningKey=新对称性安全密钥(密钥),
validateisuer=false,
ValidateAudience=false
};
});
services.AddAuthorization(选项=>
{
options.AddPolicy(“RequireAdministratorRole”,policy=>policy.RequireRole(“Administrator”);
});
//更改身份框架密码策略
配置(选项=>
{
options.Password.RequireDigit=false;
options.Password.RequiredLength=5;
options.Password.RequireLowercase=true;
options.Password.RequireUppercase=false;
options.Password.RequireNonAlphanumeric=false;
});
services.AddAntiforgery(options=>options.HeaderName=“X-XSRF-TOKEN”);
services.AddMvc(选项=>
{
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void配置(IApplicationBuilder应用程序、IHostingEnvironment环境、IServiceProvider服务提供商)
{
//设置标识
app.UseAuthentication();
更新数据库(app);
//允许所有COR
app.UseCors(x=>x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
app.UseDeveloperExceptionPage();
//强制仅在用户同意的情况下存储非必要的cookie
app.UseCookiePolicy();
//在wwwroot文件夹中启用静态文件
app.UseStaticFiles();
//设置HTTP路由
app.UseMvc(路由=>
{
//Api路由
routes.MapRoute(
名称:“api”,
模板:“api/{controller}/{action}/{moreInfo?}”);
//默认反应路线
routes.MapRoute(
名称:“默认”,
模板:“{*path}”,
默认值:新建{controller=“Home”,action=“Index”});
});
}
私有静态void UpdateDatabase(IApplicationBuilder应用程序)
{
使用(var serviceScope=app.ApplicationServices)
.GetRequiredService()
.CreateScope())
{
使用(var context=serviceScope.ServiceProvider.GetService())
{
context.Database.recreated();
}
}
}
}
.csproj:

 <Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <RuntimeFrameworkVersion>2.2.0</RuntimeFrameworkVersion>
    <AspNetCoreHostingModel>OutOfProcess</AspNetCoreHostingModel>
    <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
    <OutputType>Exe</OutputType>
  </PropertyGroup>
  <ItemGroup>
    <Compile Remove="Migrations\20181110121254_rentalInfoLeasingTypeSetNull.cs" />
    <Compile Remove="Migrations\20181110121254_rentalInfoLeasingTypeSetNull.Designer.cs" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="EPPlus.Core" Version="1.5.4" />
    <PackageReference Include="Microsoft.AspNetCore.App" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.DataProtection.EntityFrameworkCore" Version="2.2.0" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.0" />
    <PackageReference Include="Sendgrid" Version="9.10.0" />
  </ItemGroup>
  <ItemGroup>
    <Folder Include="wwwroot\Examples\" />
    <Folder Include="wwwroot\Uploads\" />
    <Folder Include="wwwroot\EmailTemplates\" />
    <Folder Include="wwwroot\React" />
    <Folder Include="wwwroot\React\media" />
  </ItemGroup>
  <ItemGroup>
    <None Include="Views\Home\Index.cshtml" />
  </ItemGroup>
  <ProjectExtensions><VisualStudio><UserProperties appsettings_1json__JSONSchema="" /></VisualStudio></ProjectExtensions>
</Project>

netcoreapp2.2
    /// <summary>
    /// Get list of all companies without their domains
    /// </summary>
    /// <returns>List of companies</returns>
    [Authorize(Roles = "Admin")]
    [HttpGet]
    public async Task<IActionResult> Get()
    {
        List<Company> companies = await _repoWrapper.Companies.GetAllAsync();
        List<CompanyListItemResponse> response = new List<CompanyListItemResponse>();

        foreach (Company company in companies)
        {
            response.Add(new CompanyListItemResponse { Id = company.Id, Name = company.Name });
        }

        response = response.OrderBy(x => x.Name).ToList();

        return Ok(response);
    }