ASP .NET MVC rewrite img src url

Viewed 34

I have images in my web app that are currently retrieved from another domain:

<img src="https://images.other.net/{folder}/{filename}"/>

I want to rewrite all image urls to a specific action in my own domain but using some parts of the path above. The new URL should look like:

<img src="https://images.mydomain.net/en/home/getimage?name={filename}&folder={folder}"/>

where folder and filename are dynamic values.

I want to see if I can do it without actually changing all paths 1 by 1. Can I do it either by MVC Routing rules or by URL rewrite rules in the web.config file?

1 Answers

Below is the list of several options to do that. This list also contains the benefits/problems you will face using these methods:

  1. Changing all paths:
    • You can change all the paths at once by using the find and replace option if the base URL of all the paths is the same.
    • The shortcut key for Find and Replace option is Ctrl + Shift + R .
    • If you will keep the base URL in multiple files/places in the code, it will create a problem for you if the URL will change in the future, you have to replace them again.
  2. Put the base URL in a web.config key (Recommended)
    • Better approach is to create a key in the web.config file and put the base URL there so that even if it changes in the future you just have to change the URL once in the web.config file.
  3. Using IIS URL Rewrite
    • You can get help from this article to create some URL rewrite rules.
    • For rewrite rule with dynamic values see this article.
Related