web.configIHttpHandler
のセクションに手動で追加する代わりに、C# コードで動的に登録する方法はありますか。system.web/httpHandlers
ばかげているように聞こえるかもしれませんが、これには十分な理由があります。Web サイトの所有者が .dll ファイルを bin ディレクトリにドロップするだけで使用できる WidgetLibrary を構築しており、web.config への最小限の構成でこれをサポートしたいと考えています。
web.configIHttpHandler
のセクションに手動で追加する代わりに、C# コードで動的に登録する方法はありますか。system.web/httpHandlers
ばかげているように聞こえるかもしれませんが、これには十分な理由があります。Web サイトの所有者が .dll ファイルを bin ディレクトリにドロップするだけで使用できる WidgetLibrary を構築しており、web.config への最小限の構成でこれをサポートしたいと考えています。
ハンドラーを変更することはできませんが、次の手順に従って、プログラムでハンドラーにルートを追加できます。
IRouteHandler を実装する
public class myHandler : IHttpHandler, IRouteHandler
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
// your processing here
}
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return this;
}
}
登録ルート:
//from global.asax.cs
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.Add(new Route
(
"myHander.axd",
new myHandler()
));
}
そこにあります。コードを介して登録されたハンドラー。:)
web.config
使用可能なハンドラーがファイルから直接読み取られ、プライベート データ構造にキャッシュされるため、AppDomain が実行された後に登録済みの HttpHandlers を変更することはできないと思います。
許可する拡張機能が事前にわかっている場合は、これらの拡張機能を 1 つの拡張機能にマップしHttpHandlerFactory
、選択したハンドラーを (動的なアセンブリの読み込みとリフレクションを使用して) 返すことができます。例えば:
<add path="*.ch1,*.ch2,*.ch3" verb="*"
type="MyHandlers.MyHandlerFactory, MyHandlers" />
実行時に変更するweb.config
と、AppDomain が再起動します。
コントロールを作成するときは、通常、ControlDesigner クラスで GetDesignTimeHtml 関数をオーバーライドします。その関数から、HttpHandler が登録されているかどうかを確認し、登録されていない場合は登録します。新しい HttpHandler を登録するために使用するコードは次のとおりです。
private void RegisterHttpHandler()
{
IWebApplication webApplication =
(IWebApplication)this.GetService(typeof(IWebApplication));
if (webApplication != null)
{
Configuration configuration = webApplication.OpenWebConfiguration(false);
if (configuration != null)
{
HttpHandlersSection section =
(HttpHandlersSection)configuration.GetSection(
"system.web/httpHandlers");
if (section == null)
{
section = new HttpHandlersSection();
ConfigurationSectionGroup group =
configuration.GetSectionGroup("system.web");
if (group == null)
{
configuration.SectionGroups.Add("system.web",
new ConfigurationSectionGroup());
}
group.Sections.Add("httpHandlers", section);
}
section.Handlers.Add(Action);
configuration.Save(ConfigurationSaveMode.Minimal);
}
}
}
Action プロパティは静的な HttpHandlerAction です