Base solution for your next web application
Open Closed

.Net Core MVC + Jquery Implentation Issues (Local & Azure) - Immediate Help Please #6296


User avatar
0
urlive created

Just a quick heads up on what I was able to acheive:

I tried to run this project both locally and on azure. I was able to run the 'update-database' command with the connection string which created the new database on both the local sql server and the azure sql server. When publishing the project I was running into these errors. (I did run the free version of .net core 2.2 abp boilerplate project and that had worked (https://aspnetboilerplate.com/Templates))

Running into an Internal Server Error when running the *.Web.mvc project locally:

Win32Exception: The system cannot find the file specified
Unknown location

SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

Raw Exception Details (Locally) System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) ---> System.ComponentModel.Win32Exception (2): The system cannot find the file specified at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource 1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource 1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource 1 retry, DbConnectionOptions userOptions) at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource 1 retry) at System.Data.SqlClient.SqlConnection.Open() at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnection(Boolean errorsExpected) at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected) at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.BeginTransaction(IsolationLevel isolationLevel) at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func 3 operation, Func 3 verifySucceeded) at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.BeginTransaction(DatabaseFacade databaseFacade, IsolationLevel isolationLevel) at Abp.EntityFrameworkCore.Uow.DbContextEfCoreTransactionStrategy.CreateDbContext[TDbContext](String connectionString, IDbContextResolver dbContextResolver) at Abp.EntityFrameworkCore.Uow.EfCoreUnitOfWork.GetOrCreateDbContext[TDbContext](Nullable 1 multiTenancySide, String name) at Abp.EntityFrameworkCore.Repositories.EfCoreRepositoryBase 3.get_Table() at Abp.EntityFrameworkCore.Repositories.EfCoreRepositoryBase 3.Insert(TEntity entity) at Abp.EntityFrameworkCore.Repositories.EfCoreRepositoryBase 3.InsertAsync(TEntity entity) at Castle.Proxies.Invocations.IRepository 2_InsertAsync_19.InvokeMethodOnTarget() at Castle.DynamicProxy.AbstractInvocation.Proceed() at Abp.Domain.Uow.UnitOfWorkInterceptor.PerformAsyncUow(IInvocation invocation, UnitOfWorkOptions options) at Castle.DynamicProxy.AbstractInvocation.Proceed() at Castle.Proxies.IRepository 2Proxy_16.InsertAsync(AuditLog entity) at Abp.Auditing.AuditingHelper.SaveAsync(AuditInfo auditInfo) at Abp.AspNetCore.Mvc.Auditing.AbpAuditActionFilter.OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync() at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync() at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextExceptionFilterAsync() at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ExceptionContext context) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter() at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync() at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync() at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext) at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext) at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context) at IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at IdentityServer4.Hosting.BaseUrlMiddleware.Invoke(HttpContext context) at Abp.AspNetZeroCore.Web.Authentication.JwtBearer.JwtTokenMiddleware.<>c__DisplayClass0_0.<<UseJwtTokenMiddleware>b__0>d.MoveNext() --- End of stack trace from previous location where exception was thrown --- at Abp.AspNetZeroCore.Web.Authentication.JwtBearer.JwtTokenMiddleware.<>c__DisplayClass0_0.<<UseJwtTokenMiddleware>b__0>d.MoveNext() --- End of stack trace from previous location where exception was thrown --- at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context) ClientConnectionId:00000000-0000-0000-0000-000000000000 Error Number:2,State:0,Class:20

When running the same project on Azure we receive a:

Http 500 error: 'domain.azurewebsites.net' is currently unmable to handle the request.

My connection string is as follows: Locally:

"Default": "Server=*my server name*;Database=coretestdb;User Id=****** ;Password= *****;"

Azure:

"Default": "Server=tcp: *my server name*.database.windows.net,1433;Initial Catalog=coretestdb;Persist Security Info=False;User ID=*****;Password=*****;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" (Azure)

Afterwards I used these connection strings within the *.Web.host project and the Swagger UI worked perfectly.

Could the issue be within my startup file (I did not alter the startup file)?

`namespace UL.Web.Startup { public class Startup { private readonly IConfigurationRoot _appConfiguration; private readonly IHostingEnvironment _hostingEnvironment;

    public Startup(IHostingEnvironment env)
    {
        _appConfiguration = env.GetAppConfiguration();
        _hostingEnvironment = env;
    }

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        //MVC
        services.AddMvc(options =>
        {
            options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
        }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        var identityBuilder = IdentityRegistrar.Register(services);

        //Identity server
        if (bool.Parse(_appConfiguration["IdentityServer:IsEnabled"]))
        {
            IdentityServerRegistrar.Register(services, _appConfiguration);
        }

        AuthConfigurer.Configure(services, _appConfiguration);

        //Swagger - Enable this line and the related lines in Configure method to enable swagger UI
        //services.AddSwaggerGen(options =>
        //{
        //    options.SwaggerDoc("v1", new Info { Title = "UL API", Version = "v1" });
        //    options.DocInclusionPredicate((docName, description) => true);
        //});

        //Recaptcha
        services.AddRecaptcha(new RecaptchaOptions
        {
            SiteKey = _appConfiguration["Recaptcha:SiteKey"],
            SecretKey = _appConfiguration["Recaptcha:SecretKey"]
        });

        //Hangfire (Enable to use Hangfire instead of default job manager)
        //services.AddHangfire(config =>
        //{
        //    config.UseSqlServerStorage(_appConfiguration.GetConnectionString("Default"));
        //});

        services.AddScoped<IWebResourceManager, WebResourceManager>();
        services.AddSignalR();

        //Configure Abp and Dependency Injection
        return services.AddAbp<ULWebMvcModule>(options =>
        {
            //Configure Log4Net logging
            options.IocManager.IocContainer.AddFacility<LoggingFacility>(
                f => f.UseAbpLog4Net().WithConfig("log4net.config")
            );

            options.PlugInSources.AddFolder(Path.Combine(_hostingEnvironment.WebRootPath, "Plugins"), SearchOption.AllDirectories);
        });
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        //Initializes ABP framework.
        app.UseAbp(options =>
        {
            options.UseAbpRequestLocalization = false; //used below: UseAbpRequestLocalization
        });

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseStatusCodePagesWithRedirects("~/Error?statusCode={0}");
            app.UseExceptionHandler("/Error");
        }

        app.UseAuthentication();

        if (bool.Parse(_appConfiguration["Authentication:JwtBearer:IsEnabled"]))
        {
            app.UseJwtTokenMiddleware();
        }

        if (bool.Parse(_appConfiguration["IdentityServer:IsEnabled"]))
        {
            app.UseJwtTokenMiddleware("IdentityBearer");
            app.UseIdentityServer();
        }

        app.UseStaticFiles();

        using (var scope = app.ApplicationServices.CreateScope())
        {
            if (scope.ServiceProvider.GetService<DatabaseCheckHelper>().Exist(_appConfiguration["ConnectionStrings:Default"]))
            {
                app.UseAbpRequestLocalization();
            }
        }

        app.UseSignalR(routes =>    
        {
            routes.MapHub<AbpCommonHub>("/signalr");
            routes.MapHub<ChatHub>("/signalr-chat");    
        });

        //Hangfire dashboard & server (Enable to use Hangfire instead of default job manager)
        //app.UseHangfireDashboard("/hangfire", new DashboardOptions
        //{
        //    Authorization = new[] { new AbpHangfireAuthorizationFilter(AppPermissions.Pages_Administration_HangfireDashboard)  }
        //});
        //app.UseHangfireServer();

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

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

        // Enable middleware to serve generated Swagger as a JSON endpoint
        //app.UseSwagger();
        // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
        //app.UseSwaggerUI(options =>
        //{
        //    options.SwaggerEndpoint(_appConfiguration["App:SwaggerEndPoint"], "UL API V1");
        //    options.InjectBaseUrl(_appConfiguration["App:WebSiteRootAddress"]);
        //}); //URL: /swagger
    }
}

}`

Please let me know if anyone has a solution, thank you.


3 Answer(s)
  • User Avatar
    0
    maliming created
    Support Team

    Publish will use the appsettings.Production.json configuration file

    https://github.com/aspnetzero/aspnet-zero-core/blob/dev/aspnet-core/src/MyCompanyName.AbpZeroTemplate.Web.Mvc/appsettings.Production.json https://github.com/aspnetzero/aspnet-zero-core/blob/dev/aspnet-core/src/MyCompanyName.AbpZeroTemplate.Web.Host/appsettings.Production.json

  • User Avatar
    0
    urlive created

    Hi, I figured out the solution to the problem. But, these two links you have posted both return a 404 error. Please look into that. Thank you

  • User Avatar
    0
    ryancyq created
    Support Team

    Hi, you need to login to github (the account that you linked with your ANZ license) to view the links.