首页 > 解决方案 > Net core 2.1 elasticsearch 在开发中工作,它在发布中不起作用

问题描述

net core 2.1 elasticsearch 在开发中工作,它在发布时不起作用,这是我的 elasticsearch 类

{public static class ElasticsearchExtensions
    {
        public static void AddElasticsearch(
            this IServiceCollection services, IConfiguration configuration)
        {
            var defaultIndex ="honadonz";


            var settings = new ConnectionSettings(new Uri("https://711e0c87a+++++++=========dc2528152891.us-east-1.aws.found.io:9243"))
                .DefaultIndex(defaultIndex)
                .BasicAuthentication("elastic", "q1vqu++++++++yfV7RFS5WR6");

            // AddDefaultMappings(settings);

            var client = new ElasticClient(settings);

            services.AddSingleton<IElasticClient>(client);

            CreateIndex(client, defaultIndex);
        }

        private static void AddDefaultMappings(ConnectionSettings settings)
        {
            settings
                .DefaultMappingFor<ElasticSearchModel>(m => m);

        }

        private static void CreateIndex(IElasticClient client, string indexName)
        {
            var createIndexResponse = client.CreateIndex("honadonz", c => c
                          .Mappings(m => m.Map<ElasticSearchModel>(mm => mm
                         .AutoMap()
                            ))
                            .RequestConfiguration(r => r
                            .DisableDirectStreaming()
    )
                  );

                   Console.WriteLine("Writeline is :" + createIndexResponse);
        }
    }
}

我在 cloud.elastic.co 中使用 Elasticsearch 6.8.1 版并嵌套 6.8.0

回复 StartUp.cs 类

 using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Threading.Tasks;
    using Autofac;
    using Autofac.Extensions.DependencyInjection;
    using AutoMapper;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    using Microsoft.Extensions.Options;
    using Swashbuckle.AspNetCore.Swagger;
    using XonadonUz.Core.Extensions;
    using XonadonUz.Core.DAL;
    using System.Net;
    using Microsoft.AspNetCore.Diagnostics;
    using Microsoft.AspNetCore.Http;
    using XonadonUz.Core.Filters;
    using Microsoft.AspNetCore.Identity;
    using XonadonUz.Core.Helpers;
    using Microsoft.AspNetCore.Http.Features;
    using Microsoft.Extensions.FileProviders;
    using Microsoft.AspNetCore.SpaServices.AngularCli;


    namespace XonadonUz
    {
        public class Startup
        {
            private readonly IConfigurationRoot _config;
            public IContainer ApplicationContainer { get; private set; }

            public Startup(IHostingEnvironment env,IConfiguration configuration)
            {
                Configuration = configuration;

                var builder = new ConfigurationBuilder()
                                  .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                                  .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                                  .SetBasePath(env.ContentRootPath);
                _config = builder.Build(); ;
            }

            public IConfiguration Configuration { get; }

            public IServiceProvider ConfigureServices(IServiceCollection services)
            {
                services.AddCustomizedMvc();
                services.AddCustomAutoMapper();
                services.AddDbContext();(Configuration.GetSection("blog"));


    services.AddSpaStaticFiles(configuration =>
                {
                    configuration.RootPath = "ClientApp/dist";
                });


                services.AddCors(option =>
                   option.AddPolicy("AllowAll", p =>
                       p.AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                   )
               );

                services.AddCustomAuthentication();
                services.AddCustomAuthorization();
                services.AddCustomIdentity();  

(Configuration.GetSection("ElasticConnectionSettings"));


             services.AddElasticsearch(Configuration);



                services.Configure<FormOptions>(x =>
                {
                    // set MaxRequestBodySize property to 200 MB
                    x.MultipartBodyLengthLimit = 209715200;
                });

                services.AddSwaggerGen(c =>
                 {
                     c.SwaggerDoc("doc", new Info { Title = "HonadonUz API" });
                     c.OperationFilter<FileOperationFilter>();
                 });

                return services.ConfigureAutofac(ApplicationContainer);
            }

            public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime)
            {
                EmailTemplates.Initialize(env);
                Core.ServiceProvider.Services = app.ApplicationServices;

                #region Configure swagger endpoints
                app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    c.RoutePrefix = AppSettings.Instance.SwaggerRoutePrefix;
                    c.SwaggerEndpoint("/swagger/doc/swagger.json", "doc");
                });
                #endregion

                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                    app.UseDatabaseErrorPage();
                }
                else{
                    app.UseExceptionHandler("/Error");
                    app.UseHsts();
                }

                // app.UseExceptionHandler(builder =>
                // {
                //     builder.Run(async context =>
                //     {
                //         context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                //         context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
                //         var error = context.Features.Get<IExceptionHandlerFeature>();
                //         if (error != null)
                //         {
                //             context.Response.AddApplicationError(error.Error.Message);
                //             await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false);
                //         }
                //     });
                // });

                app.UseHttpsRedirection();
                app.UseStaticFiles();
                app.UseSpaStaticFiles();
                app.UseStaticFiles(new StaticFileOptions()
                {
                    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "Storage")),
                    RequestPath = new PathString("/Storage")
                });
                app.UseAuthentication();
                app.UseCors("AllowAll");
                app.UseMvc();

                 app.UseSpa(spa =>
               {

                    // To learn more about options for serving an Angular SPA from ASP.NET Core,
                    // see https://go.microsoft.com/fwlink/?linkid=864501

                    spa.Options.SourcePath = "ClientApp";

                   if (env.IsDevelopment())
                   {
                       spa.UseAngularCliServer(npmScript: "start");
                       spa.Options.StartupTimeout = TimeSpan.FromSeconds(120); 

                    }
               });

            }
        }
    }

当我在 localhost 中运行它时,在我使用 aws cloud 并且它的工作没有任何问题(相同的代码)之前,现在我改为 cloud.elastic.co

csproj

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <TypeScriptToolsVersion>3.0</TypeScriptToolsVersion>

    <!-- qo'shilgan -->
     <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
    <IsPackable>false</IsPackable>
    <SpaRoot>ClientApp\</SpaRoot>
    <DefaultItemExcludes>$(DefaultItemExcludes);$(SpaRoot)node_modules\**</DefaultItemExcludes>

    <BuildServerSideRenderer>false</BuildServerSideRenderer>

    <!-- qo'shilgan -->
  </PropertyGroup>
  <ItemGroup>
    <None Remove="Core\DAL\Entities\Manual\Country.cs~RF134f573d.TMP" />
  </ItemGroup>
  <ItemGroup>
    <Folder Include="Core\Enums\" />
    <Folder Include="Seed\" />
    <Folder Include="Storage\" />
    <Folder Include="Storage\Building\Media\" />
    <Folder Include="Storage\Building\Photo\" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Autofac" Version="4.8.1" />
    <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="4.3.1" />
    <PackageReference Include="AutoMapper" Version="7.0.1" />
    <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="5.0.1" />
    <PackageReference Include="FluentValidation.AspNetCore" Version="7.5.2" />
    <PackageReference Include="MailKit" Version="2.1.0.3" />
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.8" />
    <PackageReference Include="Microsoft.AspNetCore.HttpsPolicy" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.SpaServices.Extensions" Version="2.2.0" />
    <PackageReference Include="Microsoft.CodeAnalysis.Common" Version="2.10.0" />
    <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="2.10.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.1.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.1.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="2.1.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.6" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.1.4" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.3" />
    <PackageReference Include="morelinq" Version="3.1.0" />
    <PackageReference Include="NEST.JsonNetSerializer" Version="6.8.0" />
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="2.1.2" />
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite" Version="2.1.1" />
    <PackageReference Include="OpenIddict" Version="2.0.0" />
    <PackageReference Include="OpenIddict.EntityFrameworkCore" Version="2.0.0" />
    <PackageReference Include="OpenIddict.Mvc" Version="2.0.0" />
    <PackageReference Include="PagedList.Core" Version="1.17.4" />
    <PackageReference Include="Serilog" Version="2.7.1" />
    <PackageReference Include="Serilog.Extensions.Logging" Version="2.0.2" />
    <PackageReference Include="Serilog.Sinks.Seq" Version="4.0.0" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="4.0.1" />
  </ItemGroup>
  <ItemGroup>
    <Reference Include="System">
      <HintPath>System</HintPath>
    </Reference>
    <Reference Include="System.ComponentModel.Composition">
      <HintPath>System.ComponentModel.Composition</HintPath>
    </Reference>
    <Reference Include="System.ComponentModel.DataAnnotations">
      <HintPath>System.ComponentModel.DataAnnotations</HintPath>
    </Reference>
    <Reference Include="System.Data">
      <HintPath>System.Data</HintPath>
    </Reference>
  </ItemGroup>
  <ItemGroup>
    <Service Include="{508349b6-6b84-4df5-91f0-309beebad82d}" />
  </ItemGroup>

    <!-- qo'shilgan -->
      <ItemGroup>
    <!-- Don't publish the SPA source files, but do show them in the project files list -->
    <Content Remove="$(SpaRoot)**" />
    <None Include="$(SpaRoot)**" Exclude="$(SpaRoot)node_modules\**" />
  </ItemGroup>

  <Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">
    <!-- Ensure Node.js is installed -->
    <Exec Command="node --version" ContinueOnError="true">
      <Output TaskParameter="ExitCode" PropertyName="ErrorCode" />
    </Exec>
    <Error Condition="'$(ErrorCode)' != '0'" Text="Node.js is required to build and run this project. To continue, please install Node.js from https://nodejs.org/, and then restart your command prompt or IDE." />
    <Message Importance="high" Text="Restoring dependencies using 'npm'. This may take several minutes..." />
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
  </Target>

  <Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">
    <!-- As part of publishing, ensure the JS resources are freshly built in production mode -->
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm run build --prod" />
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm run build:ssr --prod" Condition=" '$(BuildServerSideRenderer)' == 'true' " />

    <!-- Include the newly-built files in the publish output -->
    <ItemGroup>
      <DistFiles Include="$(SpaRoot)dist\**; $(SpaRoot)dist-server\**" />
      <DistFiles Include="$(SpaRoot)node_modules\**" Condition="'$(BuildServerSideRenderer)' == 'true'" />
      <ResolvedFileToPublish Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
        <RelativePath>%(DistFiles.Identity)</RelativePath>
        <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
      </ResolvedFileToPublish>
    </ItemGroup>
  </Target>
    <!-- qo'shilgan -->
</Project>

Appsettings.development.json

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

Starndart Appsettings.json

{
  "SwaggerRoutePrefix": "docs",
  "Hosts": "http://localhost:54555",
  "DatabaseConnectionString": "Data Source=SQL6005+++++++;Initial Catalog=DB_+++++++++=n;User Id=DB_+++++++======admin;Password=+++++++;", 
  "Globalization": {
    "DefaultCulture": "uz",
    "Cultures": [
      {
        "Code": "uz",
        "Name": "Uzbek",
        "IsActive": true
      },
      {
        "Code": "ru",
        "Name": "Russian",
        "IsActive": true
      },
      {
        "Code": "en",
        "Name": "English",
        "IsActive": true
      }
    ]
  },
  "JwtIssuerOptions": {
    "Issuer": "webApi",
    "Audience": "http://localhost:54555/"
  },
  "elasticsearch": {
        "index": "honadonz",
        "url": "https://=========.aws.found.io:9243"
    },
  "Storage": {
    "DefaultPhotos": "Storage/DefaultPhotos",
    "UserPhotos": "Storage/UserPhoto",
    "BuildingMedias": "Storage/Building/Media",
    "BuildingPhotos": "Storage/Building/Photo"
  },
  "SmtpConfig": {
    "Host": "smtp.gmail.com",
    "Port": 465,
    "UseSSL": true,
    "Name": "+++++++",
    "Username": "============",
    "EmailAddress": "=================",
    "Password": "==========="
  },

  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  }
}

+++++++++++++++++++++++++++++++++++错误

2019-07-28 09:54:38.745 +02:00 [警告] 无效的 NEST 响应由 POST 上的不成功 () 低级别调用构建:/honadon/_search?typed_keys=true

此 API 调用的审计跟踪:

标签: elasticsearchasp.net-core

解决方案


这个问题是托管服务提供商不允许端口 9243 上的出站连接造成的。(Smarterasp.net)他们回答我:“将您的托管帐户升级到我们的 .net 高级计划,这样您就可以启用到远程服务器的空间端口。”


推荐阅读