Click here to Skip to main content
15,886,963 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi ,

I am trying to cahce the response using cacheresponse in dot net core 2.1. I am using mvc razor pages approacch.

But the problem isit breaks between navigation from one page to other. When i redirect data from one page to other it doesnt calls that specific api related to next page. and when back to original page , butit directly display json data on browser.

What I have tried:

this was my statup.cs file where i enabled cacheresponse

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace evo_farm
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            HostingEnvironment = HostingEnvironment;
        }

        public IConfiguration Configuration { get; }
        public IHostingEnvironment HostingEnvironment { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<IISOptions>(options =>
            {
                options.ForwardClientCertificate = false;
            });

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
         .AddCookie()
         .AddOpenIdConnect("Auth0", options =>
         {
             // Set the authority to your Auth0 domain
             options.Authority = $"https://{Configuration["Auth0:Domain"]}";

             // Configure the Auth0 Client ID and Client Secret
             options.ClientId = Configuration["Auth0:ClientId"];
             options.ClientSecret = Configuration["Auth0:ClientSecret"];

             // Set response type to code
             options.ResponseType = "code";

             // Configure the scope
             options.Scope.Clear();
             options.Scope.Add("openid");

             // Set the callback path, so Auth0 will call back to http://localhost:5000/signin-auth0 
             // Also ensure that you have added the URL as an Allowed Callback URL in your Auth0 dashboard 
             options.CallbackPath = new PathString("/signin-auth0");

             // Configure the Claims Issuer to be Auth0
             options.ClaimsIssuer = "Auth0";

             // Saves tokens to the AuthenticationProperties
             options.SaveTokens = true;

             options.Events = new OpenIdConnectEvents
             {
                 //  OnRemoteFailure = OnRemoteFailure,
                 // handle the logout redirection 
                 OnRedirectToIdentityProviderForSignOut = (context) =>
              {
                  var logoutUri = $"https://{Configuration["Auth0:Domain"]}/v2/logout?client_id={Configuration["Auth0:ClientId"]}";

                  var postLogoutUri = context.Properties.RedirectUri;
                  if (!string.IsNullOrEmpty(postLogoutUri))
                  {
                      if (postLogoutUri.StartsWith("/"))
                      {
                          // transform to absolute
                          var request = context.Request;
                          postLogoutUri = request.Scheme + "://" + request.Host + request.PathBase + postLogoutUri;
                      }
                      logoutUri += $"&returnTo={ Uri.EscapeDataString(postLogoutUri)}";
                  }

                  context.Response.Redirect(logoutUri);
                  context.HandleResponse();

                  return Task.CompletedTask;
              }
             };
         });


            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.AddResponseCaching(options =>
            // {
            //     options.UseCaseSensitivePaths = true;
            // });
            
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddMvc().AddRazorPagesOptions(options =>
            {
                options.Conventions.AddPageRoute("/MainPage", "");
            });
            services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
        }

        private Task OnRemoteFailure(RemoteFailureContext context)
        {

            if (context.Failure.Message.Contains("Correlation failed"))
            {
                context.Response.Redirect("/MainPage"); // redirect without trailing slash
                context.HandleResponse();
            }
            return Task.CompletedTask;
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            // app.UseCookiePolicy(new CookiePolicyOptions()
            // {
            //     HttpOnly = HttpOnlyPolicy.Always,
            //     Secure = CookieSecurePolicy.Always,
            //     MinimumSameSitePolicy = SameSiteMode.Strict
            // });

            app.UseCorsMiddleware();
            app.UseAuthentication();
            app.UseCors("CorsPolicy");
            // app.UseResponseCaching();
    //         app.Use(async (context, next) =>
    // {
    //     // For GetTypedHeaders, add: using Microsoft.AspNetCore.Http;
    //     context.Response.GetTypedHeaders().CacheControl =
    //         new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
    //         {
    //             Public = true,
    //             MaxAge = TimeSpan.FromSeconds(120)
    //         };
    //         context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.Vary] =
    //         new string[] { "Accept-Encoding" };

    //     await next();
    // });
            app.UseMvc();
            //app.UseMvc(rb =>
            //{
            //    rb.MapRoute(
            //        name: "default",
            //        template: "{controller}/{action}/{id?}",
            //        defaults: new { controller = "Home", action = "Index" });
            //});
        }
    }
}
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900