Remove image from Browser Cache when Image changes using Asp.Net C# and Vb.Net

Browsers, cache images and other static assets on a website, to reduce upload time and bandwidth. This process helps websites load faster, by extracting contents from the cache (a temporary storage in your computer). However, sometimes you need clear the browser cache, if the websites contents change frequently, such as images. I am sharing a simple trick here, which shows how to load clear browser cache when image changes using Asp.Net C# and Vb.Net.

Browsers, cache images and other static assets on a website, to reduce upload time and bandwidth. This process helps websites load faster, by extracting contents from the cache (a temporary storage in your computer). However, sometimes you need clear the browser cache, if the websites contents change frequently, such as images. I am sharing a simple trick here, which shows how to load clear browser cache when image changes using Asp.Net C# and Vb.Net.

I was recently updating my Easy Image Resizer tool, and I noticed that every time I select an image for resizing or cropping, the browser shows the previously selected image, instead of the new image. This is the browser’s default behavior. I had to overcome this issue and I figured out that the solution to this problem is simple. It’s a trick rather.

Browsers don’t scan every image (or any content) to check if it’s the same as before. Browser cache works by identifying objects, such as images, by its name.

Since I am using Asp.Net, I can simply change the name of the image at the server side itself, by concatenating the image name with date and time (since its always unique), and send the image (with a new name every time) to the browser.

Here’s how you should do this.

The Markup

<img id="myImage" alt="image" src="" style="border:none;max-width:100%;" runat="server" />


Code in C#

protected void Page_Load(object sender, EventArgs e)
{
     myImage.Src = "";
     myImage.Src = "~/car.png" + "?" + DateTime.Now.Ticks.ToString();    // Add date time to prevent caching.
}

Here's how it shows the image name in the browser console window.

The code concatenates a new date and time with the image name for every page load, thereby receiving a new source name for the same image.

Note: If you have a habbit of storing your images into a database, this technique useful. Simply, concatenate the date and time with image name and save it. Date and time are always different.

Vb.Net

myImage.Src = ""
myImage.Src = "~/car.png" & "?" & DateTime.Now.Ticks.ToString    ' Add date time to prevent caching.

This process is simple, and you can easily get the name of the image by simply replacing the string after the ? character.

Well, that’s it. Thanks for reading.

Introduction to ASP.NET Core Tutorials | ASP.NET Training | Simpliv

Introduction to ASP.NET Core Tutorials | ASP.NET Training | Simpliv

This course is designed you give you a deep understanding of modern .NET concepts without confusing you or making you lost in the sea of .net technologies that keep springing up now and then. Get behind the modern .NET directions and grasp all that is going on nowadays in the world of .NET.

Description
Last years a great number of technologies came up to the world of .NET platform: nowadays we have the full (classic) .NET framework with CLR as a runtime, Mono with its own runtime, .NET Core with Core CLR, WinRT, UWP and Xamarin, a new JIT compiler RyuJit, .NET Standard, PCL, .Net Native, new Roslyncompiler with open API, NuGet based project management. God’s sake! It’s so simple to get lost in that ocean of technologies. You need to understand the overall picture to feel comfortable today. Didn’t you feel like a small fish in the ocean last time? Well, I did. I questioned myself, "what the hell is going on around me?" I didn’t quite understand the directions in which technologies develop. I didn’t know what to expect, what to learn next. In such situation, you feel helpless. And what we are going to do in the course is that we’re going to eliminate this nasty feeling of being helpless by learning all the most important notions in the modern .NET platform.

Teaching Approach

No fluff, no ranting, no beating the air. I esteem your time. The course material is succinct, yet comprehensive. All important concepts are covered. For absolute beginners, I offer my help on Skype absolutely free if requested. Don't forget that this course has English subtitles, so if you don't understand my accent, feel free to turn them on.

Take this course and you will be satisfied.

Build a deep understanding of modern .NET concepts

If you go behind the modern .NET directions, then this course is for you. This course will bring a whole picture of what's going on nowadays in the world of .NET, so you'll understand what you can and what you can't achieve using specific technologies. This course is like a navigation map.

Content and Overview

The goal of this course is to reveal the whole picture of the .NET world. One of the most profound technologies is the new .NET Core platform, so learning it, is a second primary goal of this course.

Of course, all the way along we will discuss all the other technologies I mentioned above.

This course is built for all kind of C# developers who are interested in learning the .NET platform. This course is beneficial for juniors as well as for seniors who want to stay well-informed about modern .NET platform. I’m sure any student will find something interesting and useful in this course.

The main prerequisite is to be familiar with development on the .NET platform in C#. That’s all you need.

In short, the course covers the following topics:

Classic .net platform, it’s building blocks, the history of this platform
Mono platform, it’s building blocks. You’ll figure out if classic .NET and Mono are compatible. We will compare classic .NET framework and Mono platform
.NET Core is the new cross-platform .NET platform. We will understand what’s different here comparing to other .NET platform and this platform means for the future of the .NET world platform
.NET Native is an interesting ahead-of-time compilation technology. You’ll know that a form of .NET Native comes to .NET Core as well.
Do you really understand what is UWP? How it is related to WinRT and what WinRT actually is?
Roslyn as a compiler platform
NuGet as a system of dependencies management
Installation of .NET Core
Command-Line Interface (CLI) of .NET Core
Deployment in .NET Core: SCD and FDD
The problem of cross-compiling
Portable Class Library (PCL)
.NET Standard
.NET Portability Analyzer
Unit-Testing in .NET Core
Upcoming Changes quick overview
How long is this course: The course is around 2 hours. All are video lectures. You will be able to download all the slides and code samples used in the course.

Keywords related to the course:

.NET Core
C#.NET Core
.NET Standard
NuGet
Core CLR
.NET Ecosystem
Who is the target audience?

Anyone from beginner to senior
Basic knowledge
Need to be familiar with development on the .NET platform in C#
What will you learn
Create, deploy and manage .NET Core applications
Disctinct different technologies: platforms, runtimes, compilers and so on
Create and use .NET Standard Libraries
Understand all the modern .NET concepts
Write unit-tests in .NET Core
To continue:

Create Login and Registration in Your ASP.NET Core MVC App

Create Login and Registration in Your ASP.NET Core MVC App

This tutorial walks you through setting up login and registration with ASP.NET Core MVC. In this tutorial, you learned how to add authentication to your ASP.NET Core MVC app and allow users to register for a new account.

This tutorial walks you through setting up login and registration with ASP.NET Core MVC. In this tutorial, you learned how to add authentication to your ASP.NET Core MVC app and allow users to register for a new account.

User authentication and authorization are common features in web applications, but building these mechanics has the potential to take a lot of time. Doing so requires setting up persistent storage for user information (in some type of database) and paying keen attention to potential security issues around sensitive operations like hashing passwords, password reset workflows, etc. - weeks of development time begin to add up before we ever get to the functionality that delivers value to your users.

In this post, we’ll walk through how Okta simplifies this process for us and set up a simple integration for an ASP.NET Core MVC app using the Okta NuGet package. We’ll build functionality for users to register for new accounts and login with their Okta credentials.

Scaffold Your ASP.NET Project

To follow along with this tutorial start by creating a new app in the console:

mkdir MyOktaProject
cd MyOktaProject
dotnet new mvc


Configure User Registration

If you don’t already have one, you’ll need to create an Okta developer account. Doing so will give you a URL for your organization called an “Okta domain”. It will also allow you to create your login credentials for accessing the Okta dashboard.

Upon submission of this form, you will receive an email Okta with instructions to obtain your credentials and complete your registration.

Execute the following steps to configure Okta so that users can register themselves for an account.

  1. From the Administrative Dashboard, hover over Users and click Registration
  2. Click Enable Registration
  3. Save the changes

Configure Basic User Authentication

Once you have access to your account you can proceed to the Dashboard using a link like the one below:

<span

class="okta-preview-domain">https://{yourOktaDomain}/admin/dashboard

On the Dashboard, click Applications in the main menu and on the Application screen, click Add Application.

Select Web then click Next.

On the Create New Application screen, set the following values:

Click Done, then click Edit next to General Settings on your newly created Okta app. Edit the following values:

Logout redirect URIs: https://localhost:5001/signout-callback-oidc

Initiate login URI: https://localhost:5001/authorization-code/callback

Add .NET Authentication Dependencies

Once your account is set up you need to add the Okta.Sdk library to your project. This post will take the approach of using the NuGet package, but the Github repository for Okta.AspNetCore can be found here.

To proceed simply search for the latest version of the Okta.Sdk NuGet package in your IDE of choice (version 1.2.0 at the time of this publication) and install it. If you’re using Visual Studio you can do this by right-clicking on the project in the solution explorer and selecting Manage NuGet Packages. For those of you not using Visual Studio, add the package via console window using the following command:

dotnet add package Okta.Sdk --version 1.2.0


Configure Your ASP.NET App for Login

Authentication works by redirecting users to the Okta website, where they will log in with their credentials, and then be returned to your site via the URL you configured above.

Add the following code to your appsettings.json file:

  "Okta": {
    "Issuer": "https://{yourOktaDomain}/oauth2/default",
    "ClientId": "{yourClientId}",
    "ClientSecret": "{yourClientSecret}"
  }


You can find each of the actual values needed to replace the settings in the config above in the following places:

ClientId refers to the client ID of the Okta application ClientSecret refers to the client secret of the Okta application Issuer will need the text {yourOktaDomain} replaced with your Okta domain, found at the top-right of the Dashboard page

Add some using statements to your Startup.cs file:

using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;


Add the following code to the top of the ConfigureServices method in your Startup.cs file:

services.AddAuthentication(sharedOptions =>
{
    sharedOptions.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
    .AddCookie()
    .AddOpenIdConnect(options =>
    {
        options.ClientId = Configuration["okta:ClientId"];
        options.ClientSecret = Configuration["okta:ClientSecret"];
        options.Authority = Configuration["okta:Issuer"];
        options.CallbackPath = "/authorization-code/callback";
        options.ResponseType = "code";
        options.SaveTokens = true;
        options.UseTokenLifetime = false;
        options.GetClaimsFromUserInfoEndpoint = true;
        options.Scope.Add("openid");
        options.Scope.Add("profile");
        options.TokenValidationParameters = new TokenValidationParameters
        {
            NameClaimType = "name"
        };
    });


In the Configure() method of your Startup.cs file add this line just before the app.UseMvc() method:

app.UseAuthentication();


Add the following MeViewModel to the Models directory:

using System.Collections.Generic;

namespace OktaAspNetCoreMvc.Models
{
    public class MeViewModel
    {
        public string Username { get; set; }

        public bool SdkAvailable { get; set; }

        public dynamic UserInfo { get; set; }

        public IEnumerable<string> Groups { get; set; }
    }
}


Add Login to Your ASP.NET App

Now that all the configuration and plumbing is done, you’re ready to add the code that will actually log users into your application.

Add the following AccountController to the Controller directory.

The controller exposes the Login() action. If the user has already been authenticated, the Login() action will redirect them to the home page. Otherwise, it will redirect them to the Okta login screen.

using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Mvc;
using Okta.Sdk;

namespace OktaAspNetCoreMvc.Controllers
{
    public class AccountController : Controller
    {
        private readonly IOktaClient _oktaClient;

        public AccountController(IOktaClient oktaClient = null)
        {
            _oktaClient = oktaClient;
        }

        public IActionResult Login()
        {
            if (!HttpContext.User.Identity.IsAuthenticated)
            {
                return Challenge(OpenIdConnectDefaults.AuthenticationScheme);
            }

            return RedirectToAction("Index", "Home");
        }
    }
}


Add the following code to your _Layout.cshtml file, just below the main menu to add the login button, or a welcome message, based on the current user’s status.:

   @if (User.Identity.IsAuthenticated)
    {
        <ul class="nav navbar-nav navbar-right">
            <li><p class="navbar-text">Hello, @User.Identity.Name</p></li>
        </ul>
    }
    else
    {
        <ul class="nav navbar-nav navbar-right">
            <li><a asp-controller="Account" asp-action="Login">Log in</a></li>
        </ul>
    }


For information on user authorization using Okta groups check out Lee Brandt’s article on user authorization in ASP.NET Core with Okta.

Register Users

If you following the instructions above to enable self-service registration the “Don’t have an account? Sign Up” message will appear at the bottom of the login form. In the next step, you’ll run the application.

Log In Using ASP.NET

That’s it! To run your solution open up a terminal and enter the following command:

dotnet run


Then navigate to http://localhost:5001 in your browser and enjoy!

The source code for this tutorial is available on GitHub.

Now you have a website with a working login and user registration form. Your website also allows users to recover lost passwords. By repeating these steps you can create a network of tools that your users can access all with the same login.

Learn More

The Complete ASP.NET MVC 5 Course

Build a Real-world App with ASP.NET Core and Angular 2 (4+)

ASP NET Core (ASP.NET 5),MVC 6,C#,Angular2 & EF Crash Course

Rest Api’s in Asp.Net and C#

Hands on ASP .Net Core 2

DevOps For ASP.NET Developers

DevOps is the union of people, process, and products to enable continuous delivery of value to our end users. Azure DevOps is everything you need to turn an idea into a working piece of software.


Abel and Jeremy introduce us the benefits of DevOps. They give us a high level overview of how to implement some DevOps best practices using Azure DevOps.

Abel and Jeremy explain the difference between these two options and show how we can get started with Azure Repos. They will walk us through creating branches, adding policies, and also integrating with GitHub.

Thanks for reading ❤

If you liked this post, share it with all of your programming buddies!

Follow me on Facebook | Twitter

Learn More

The Complete ASP.NET MVC 5 Course

Build a Real-world App with ASP.NET Core and Angular 2 (4+)

Build an app with ASPNET Core and Angular from scratch

Introduction to ASP.NET Core 2.2

Build a REST API with ASP.NET Core 2.2

Build amazing web apps with ASP.NET Core 3.0

Angular and .NET Core

Building Web App using ASP.NET Web API Angular 7 and SQL Server