简体   繁体   中英

How can I set common headers of a virtual directory in IIS through C#?

在此处输入图像描述 I have to set the "Expire Web Content" value of a virtual directory to "Immediately". This is possible through IIS but I want to achieve the same result with a C# script.

How can I do this? Any clue?

You could achieve this by changing system.webServer/staticContent/CacheControlMode to DisableCacheControl.

There are two ways to achieve this.

1.If you want to set it in Site/MyVirtualDIR/web.config

using System;
using System.Text;
using Microsoft.Web.Administration;

internal static class Sample {

    private static void Main() {

        using(ServerManager serverManager = new ServerManager()) { 
            Configuration config = serverManager.GetWebConfiguration("Default Web Site" , "MyVirtualDir");

            ConfigurationSection staticContentSection = config.GetSection("system.webServer/staticContent");

            ConfigurationElement clientCacheElement = staticContentSection.GetChildElement("clientCache");
            clientCacheElement["cacheControlMode"] = @"DisableCache";

            serverManager.CommitChanges();
        }
    }
}

2.If you want to Set it in root web.config/location:

using System;
using System.Text;
using Microsoft.Web.Administration;

internal static class Sample {

    private static void Main() {

        using(ServerManager serverManager = new ServerManager()) { 
            Configuration config = serverManager.GetWebConfiguration("Default Web Site");

            ConfigurationSection staticContentSection = config.GetSection("system.webServer/staticContent", "MyVirtualDir");

            ConfigurationElement clientCacheElement = staticContentSection.GetChildElement("clientCache");
            clientCacheElement["cacheControlMode"] = @"DisableCache";

            serverManager.CommitChanges();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM