3

I am using browserlink to edit CSS styles and it works pretty nice. Unfortunately, if I change something in .cshtml files, my browser automatically refresh on save, but changes are not visible.

If I close my application and open again, changes are visible. It seems like my application is caching views somehow somewhere and not reloading changes I do into my files.

This is really not a browser caching problem. The application really sends unchanged html result.

How can I disable such a caching feature in development?

I am using latest ASP NET Core MVC libraries.

EDIT: if I change anything in _layout, the website is updated without any problem.

EDIT 2: Startup functions

        public void ConfigureServices(IServiceCollection services)
    {
        services.AddWebSocketManager();

        var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
        var path = System.AppDomain.CurrentDomain.BaseDirectory;

        var machineName = Environment.MachineName;
        var confBuilder = new ConfigurationBuilder();
        IConfigurationBuilder conf = confBuilder.SetBasePath(path);

        if (env == "Development")
        {
            conf = conf.AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true);
            conf = conf.AddJsonFile($"appsettings.Development.json", optional: true, reloadOnChange: true);
            conf = conf.AddJsonFile($"appsettings.{machineName}.json", optional: true, reloadOnChange: true);
            conf = conf.AddJsonFile($"appsettings.External.json", optional: true, reloadOnChange: true);
        }
        else
        {
            conf = conf.AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true);
            conf = conf.AddJsonFile($"appsettings.Production.json", optional: true, reloadOnChange: true);
            conf = conf.AddJsonFile($"appsettings.External.json", optional: true, reloadOnChange: true);
        }
        Configuration = conf.Build();
        services.AddSingleton(provider => Configuration);

        CoreStarter.OnServiceConfiguration?.Invoke(Configuration, services);

        var settings = new JsonSerializerSettings();
        settings.ContractResolver = new SignalRContractResolver();
        var serializer = JsonSerializer.Create(settings);
        services.Add(new ServiceDescriptor(typeof(JsonSerializer),provider => serializer,ServiceLifetime.Transient));

        services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.TryAddSingleton<IContextService, ContextService>();
        services.TryAddSingleton<ICryptoService, CryptoService>();
        services.TryAddSingleton<IAuthorizationHandler, AuthenticationHandler>();
        services.TryAddSingleton<IHttpService, RestApiService>();

        if (services.Any(x => x.ServiceType == typeof(IIdentityService)))
        {
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
            {
                options.Events.OnRedirectToLogin = (context) =>
                {
                    context.Response.StatusCode = 401;
                    return Task.CompletedTask;
                };
                options.Events.OnRedirectToAccessDenied = (context) =>
                {
                    context.Response.StatusCode = 401;
                    return Task.CompletedTask;
                };

                var sharedCookiePath = Configuration.GetJsonKey<string>("SharedCookiePath");
                if (!String.IsNullOrWhiteSpace(sharedCookiePath))
                {
                    options.DataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(sharedCookiePath));
                }
            });
        }


        services.AddCors();
        services.AddLogging(builder =>
        {
            builder.AddConsole().AddDebug();
        });
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info {Title = "CoreR API", Version = "v1"});
        });

        services.AddDistributedMemoryCache();
        services.AddSession();
        services.AddMemoryCache();
        services.AddSingleton<IAssemblyLocator, BaseAssemblyLocator>();
        services.AddSignalR(options =>
        {
            options.Hubs.EnableDetailedErrors = true;
        });

        var mvcBuilder = services.AddMvc(config =>
        {
            if (services.Any(x => x.ServiceType == typeof(IIdentityService)))
            {
                var policyBuilder = new AuthorizationPolicyBuilder();
                policyBuilder.RequireAuthenticatedUser();
                policyBuilder.AddRequirements(new AuthenticationRequirement());

                var policy = policyBuilder.Build();
                config.Filters.Add(new AuthorizeFilter(policy));
            }
        })
        .AddJsonOptions(options =>
        {
            options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        });

        var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();

        foreach (var assembly in assemblies)
        {
            mvcBuilder.AddApplicationPart(assembly);
        }

        ServiceProvider = services.BuildServiceProvider();
    }

    public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider, IHostingEnvironment env)
    {
        var embeddedProvider = new EmbeddedFileProvider(Assembly.GetExecutingAssembly());
        var physicalProvider = env.ContentRootFileProvider;
        var compositeProvider = new CompositeFileProvider(physicalProvider, embeddedProvider);


        app.UseCors(o => o.AllowAnyOrigin().AllowCredentials().AllowAnyMethod().AllowAnyHeader());
        app.UseAuthentication();

        app.UseBrowserLink();
        app.UseDeveloperExceptionPage();

        app.UseDefaultFiles(new DefaultFilesOptions()
        {
            FileProvider = compositeProvider,
            DefaultFileNames = new List<string>() { "default.html"},
        });
        app.UseStaticFiles(new StaticFileOptions {FileProvider = compositeProvider});
        app.UseSession();
        app.UseWebSockets();
        app.UseSignalR();
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "CoreR API");
        });

        app.UseMvc(routes =>
        {
            routes.MapRoute("Default", "api/{controller}/{action}/{id?}");
        });

        CoreStarter.OnConfiguration?.Invoke(Configuration, app, serviceProvider, env);
    }
Set
  • 47,577
  • 22
  • 132
  • 150
wh1sp3r
  • 1,640
  • 2
  • 17
  • 30
  • No caching happens out of the box. However, if you've added something like the Response Caching Middleware, then that might be an issue. Show us your Startup.cs. – Chris Pratt Mar 21 '18 at 13:11
  • I added some startup functions, they are a bit big hehe – wh1sp3r Mar 21 '18 at 13:56
  • The only thing I see that could potentially be a problem is `UseDefaultFiles`, which uses the static files middleware to actually serve your static HTML files. If it's actually `default.html` that's not refreshing, it's possible it's being cached by the browser. (It will look as if the server is sending the same response if the browser is just using the cache directly). – Chris Pratt Mar 21 '18 at 14:05
  • all cshtml files are not refreshing until app restart. if I change layout.cshtml. it's refreshed fine – wh1sp3r Mar 21 '18 at 14:25
  • 1
    Is this the same issue? https://stackoverflow.com/questions/53639969/net-core-mvc-page-not-refreshing-after-changes – Dai Aug 23 '19 at 03:08

1 Answers1

5

according to Razor file compilation in ASP.NET Core If you want enable run time compilation only for local development:

1.Conditionally reference the Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation package based on the active Configuration value:

<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="3.1.0" Condition="'$(Configuration)' == 'Debug'" />

2. Update the project's Startup.cs file ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
    IMvcBuilder builder = services.AddRazorPages();

    if (env.IsDevelopment())
    {
        builder.AddRazorRuntimeCompilation();
    }
}
ali-myousefi
  • 822
  • 2
  • 11
  • 26
  • I had no idea you could conditionally add a NuGet package! Since ASP.NET Core 3.1, though, this can be done by editing the `launchSettings.json` file instead of the `Startup.cs` file: https://learn.microsoft.com/en-us/aspnet/core/mvc/views/view-compilation?view=aspnetcore-3.1&tabs=visual-studio#conditionally-enable-runtime-compilation-in-an-existing-project – Doug Mar 24 '21 at 12:49