接着我们要在WebRole中创建一个HttpModuler来检测用户的访问和并且将禁止的request扔到错误处理的页面中去:
FileManagerModuler.cs
- public void Init(HttpApplication context)
- {
- context.BeginRequest += new EventHandler(this.Application_BeginRequest);
- }
- /// <summary>
- /// Check file types and request it by cloud blob API.
- /// </summary>
- /// <param name="source"></param>
- /// <param name="e"></param>
- private void Application_BeginRequest(Object source,EventArgs e)
- {
- string url = HttpContext.Current.Request.Url.ToString();
- string fileName = url.Substring(url.LastIndexOf('/') + 1).ToString();
- string extensionName = string.Empty;
- if (fileName.Substring(fileName.LastIndexOf('.') + 1).ToString().Equals("aspx"))
- {
- return;
- }
- if (!fileName.Equals(string.Empty))
- {
- extensionName = fileName.Substring(fileName.LastIndexOf('.') + 1).ToString();
- if (!extensionName.Equals(string.Empty))
- {
- string contentType = this.GetContentType(fileName);
- if (contentType.Equals(string.Empty))
- {
- HttpContext.Current.Server.Transfer("NoHandler.aspx");
- };
- {
- FileDataSource dataSource = new FileDataSource();
- string paritionKey = this.GetPartitionName(extensionName);
- if (String.IsNullOrEmpty(paritionKey))
- {
- HttpContext.Current.Server.Transfer("NoHandler.aspx");
- }
- FileEntity entity = dataSource.GetEntitiesByName(paritionKey, "Files/" + fileName);
- if (entity != null)
- HttpContext.Current.Response.Redirect(entity.FileUrl);
- else
- HttpContext.Current.Server.Transfer("NoResources.aspx");
- }
- }
- }
- }
- /// <summary>
- /// Get file's Content-Type.
- /// </summary>
- /// <param name="filename"></param>
- /// <returns></returns>
- public string GetContentType(string filename)
- {
- string res = string.Empty;
- switch (filename.Substring(filename.LastIndexOf('.') + 1).ToString().ToLower())
- {
- case "jpg":
- res = "image/jpg";
- break;
- case "css":
- res = "text/css";
- break;
- }
- return res;
- }
- /// <summary>
- /// Get file's partitionKey.
- /// </summary>
- /// <param name="extensionName"></param>
- /// <returns></returns>
- public string GetPartitionName(string extensionName)
- {
- string partitionName = string.Empty;
- switch(extensionName)
- {
- case "jpg":
- partitionName = "image";
- break;
- case "css":
- partitionName = "css";
- break;
- }
- return partitionName;
- }
