Redis Cache not working with Asp.net core - asp.net-mvc

I try to implement redis cache in Asp.Net Core Application but its not Set any value in HttpContext.Session and not even return any value.This is my startup.cs file.
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedRedisCache(options =>
{
options.InstanceName = Configuration.GetValue<string>("redis:name");
options.Configuration = Configuration.GetValue<string>("redis:host");
});
services.AddSession(o=> { o.IdleTimeout = TimeSpan.FromMinutes(5); });
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseSession();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
Appsetting.json
"redis": {
"host": "redis-17930.c1.ap-southeast-1-1.ec2.cloud.redislabs.com",
"port": 17930,
"name": "Astroyogi"
},
HomeController.cs
public IActionResult Index()
{
var helloRedis = Encoding.UTF8.GetBytes("Hello Redis");
HttpContext.Session.Set("hellokey", helloRedis);
var getHello = default(byte[]);
HttpContext.Session.TryGetValue("hellokey", out getHello);
ViewData["Hello"] = Encoding.UTF8.GetString(getHello);
return View();
}
and the lib which i installed-
Microsoft.Extensions.Caching.Redis
Microsoft.AspNetCore.Session
and its will not set any value in session.
Please help me where i am stucking.

You cannot both set and get the value you just set in the Session in the same request. Session requires a cookie to be set, which will only happen after you return the response. On the next request, you should be able to access your value fine.

Related

MVC Routing not working in Blazor client side application

I'm trying to implement a simple MVC controller in my Blazor WASM project, but I can't get the routing to work correctly. It always redirects me to the blazor "NotFound" component when I try to access it. I've spent alot of time trying configuring in my Startup.cs but I'm run out of ideas. I'm doing this on a boilerplate WASM project in .NET6. This is how my Startup.cs looks like:
public void ConfigureServices(IServiceCollection services)
{
services.ConfigureApplicationServices();
services.ConfigurePersistenceServices(Configuration);
//services.AddMvc();
services.AddControllersWithViews();
services.AddRazorPages();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseMigrationsEndPoint();
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseMiddleware<ExceptionMiddleware>();
app.UseCors(config =>
config
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
//.WithExposedHeaders("header1", "header")
);
app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseIdentityServer();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapDefaultControllerRoute();
endpoints.MapRazorPages();
endpoints.MapFallbackToFile("index.html");
});
}
And this is my MVC controller:
[Route("[controller]/[action]")]
public class RoleManagerController : Controller
{
private readonly RoleManager<IdentityRole> _roleManager;
public RoleManagerController(RoleManager<IdentityRole> roleManager)
{
_roleManager = roleManager;
}
public async Task<IActionResult> Index()
{
var roles = await _roleManager.Roles.ToListAsync();
return View(roles);
}
[HttpPost]
public async Task<IActionResult> AddRole(string roleName)
{
if (roleName != null)
{
await _roleManager.CreateAsync(new IdentityRole(roleName.Trim()));
}
return RedirectToAction("Index");
}
}
[Polite] There's must be some missing information in your question.
I've tested this using the Net6.0 out-of-the-box Blazor Hosted template and it works.
Here's my controller:
[ApiController]
[Route("[controller]/[action]")]
public class MyController : ControllerBase
{
public string Index()
{
return "hello. You called Index";
}
}
My (out-of-the-box) Program:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.MapRazorPages();
app.MapControllers();
app.MapFallbackToFile("index.html");
app.Run();
And the Postman result (using small letters):

how to set identity page by default and and after login it redirect to perticular page

I have added identity in asp.net core 3.1, How can i set identity login page as default and after successfully login it should redirect to particular page ?
In the Public void ConfigureServices(IServiceCollection services) method add the following codes at the bottom:
services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(15);
options.LoginPath = "/Identity/Account/Login";
options.AccessDeniedPath = "/Identity/Account/AccessDenied";
options.SlidingExpiration = true;
});
Note the LoginPath and AccessDeniedPath properties. Change the other properties to fit your requirements.
For the redirection it is actually coded in the login action which will redirect the user to a specific page. On successful login write the followings to redirect to the root page:
returnUrl = returnUrl ?? Url.Content("~/");
return LocalRedirect(returnUrl);
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddRazorPages();
services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(15);
options.LoginPath = "/Identity/Account/Login";
options.AccessDeniedPath = "/Identity/Account/AccessDenied";
options.SlidingExpiration = true;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}

asp.net core app not serving ApiController route path

My asp.net core web application is not serving the ApiController route I have setup, however it used to work but I didn't change anything so idk why its not working now.
When I navigate to https://localhost:5001/api/Demo; it returns me to my sites homepage instead of running the action and displaying the data. the url in the address bar does change to …:5001/api/Demo, but does not display the data.
// controller
[ApiController]
[Route("api/[controller]")]
public class DemoController : ControllerBase
{
[HttpGet]
public string Index(string result)
{
return "test string";
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "api/{controller=Demo}/{action=Index}/{result?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
}
==============================================
UPDATE: add configure method from startup class

Pass TempData between Contollers for Modal return Null?

I want to pass Some String between two controllers to show successful login with modal.I read this topics :
ViewBag, ViewData and TempData
and
RedirectToAction with parameter
but it doesn't work for me and TempData returns Null.it's works fine in this Controllers.
public async Task<IActionResult> LoginConfirm(LoginViewModel model)
{
ApplicationUser user = await userManager.FindByNameAsync(model.Email);
if (user!=null)
{
var status = await signInManager.PasswordSignInAsync(user, model.Pass,model.RememberMe,true);
if (status.Succeeded)
{
TempData["msg"] = "You Login successful ";
return RedirectToAction("Index","Home");
}
}
TempData["msg"] = "Somethings Wrong!";
return View("Login");
}
you have two way
1)
when you using the
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;
});
you enable the GDPR ( General Data Protection Regulation ) And so for as long as the user does not accept your cookie, you will not be able to set cookie in site. And that makes the TempData empty.
2)
After Migrating to ASP Core 2.1 I had this issue and after working for a day find the solution:
in Startup.Configure() app.UseCookiePolicy(); should be after app.UseMVC();
namespace GiftSite
{
public class Startup
{
public Startup(IConfiguration configuration)
{
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)
{
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.AddAuthentication();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// 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("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
//app.UseHttpMethodOverride();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}

asp.net core mvc cors request denied [duplicate]

This question already has answers here:
ASP.NET 5: Access-Control-Allow-Origin in response
(2 answers)
Closed 6 years ago.
I've been working on a new mvc core application where I'm using core as my backend, and I'm using react as my front end.
I've started running into problems with cors where I am unable to post anything from my react fronted into my mvc core backend. Looking into the documentation has not been very helpful and even taking a "scorched earth" approach by allowing everything:
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
});
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
});
isn't helping either and now I've no idea what is really happening other than my post requests are being rejected.
My action looks as follows:
[HttpPost("_api/admin/monitor-customer")]
public IActionResult SetCustomerMonitor([FromBody]UpdateMonitor model){
try
{
var customer = Customers.Single(c => c.CustomerId == model.Id);
customer.IsMonitored = !customer.IsMonitored;
_context.SaveChanges();
return Json(new { success = true });
} catch(Exception ex){
_logger.LogDebug(ex.Message, null);
return Json(new { success = false });
}
}
My post request from react is as follows:
updateCustomer = (e) => {
var customerId = e.target.value;
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
url: "http://localhost:5000/_api/admin/monitor-customer",
data: JSON.stringify({ Id: customerId }),
dataType: "json"
});
}
Also include is my Startup.cs
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
ILogger _logger;
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AlertContext>(options => options.UseSqlite(Configuration.GetConnectionString("DefaultSqlite")));
//services.AddDbContext<AlertContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddScoped<DbContext, AlertContext>();
services.AddSingleton<IDmsService>(new DmsService());
services.AddMvc();
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
});
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseCors(options => options.AllowAnyHeader());
app.UseCors(options => options.AllowAnyMethod());
app.UseCors(options => options.AllowAnyOrigin());
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
Problem solved due to where core is enabled.
service.AddCors() must precede services.AdMvc() in the ConfigureServices methods, and the same holds true for the Configure() method. app.UseCors() must be called before app.UseMvc()
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AlertContext>(options => options.UseSqlite(Configuration.GetConnectionString("DefaultSqlite")));
//services.AddDbContext<AlertContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddScoped<DbContext, AlertContext>();
services.AddSingleton<IDmsService>(new DmsService());
// Add service and create Policy with options
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials() );
});
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
// global policy - assign here or on each controller
app.UseCors("CorsPolicy");
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}

Resources