如何从RoleEntryPoint.OnStart()获取WebRole站点根路径?

maw*_*tex 9 azure azure-web-roles

作为在Windows Azure上启动WebRole的一部分,我想访问正在启动的网站上的文件,我想在RoleEntryPoint.OnStart()中执行此操作.例如,这将使我能够在加载ASP.NET AppDomain之前影响ASP.NET配置.

当使用Azure SDK 1.3和VS2010在本地运行时,下面的示例代码可以解决这个问题,但是代码有很多黑客攻击,而且在部署到Azure时它不会起作用.

  XNamespace srvDefNs = "http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition";
  DirectoryInfo di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
  string roleRoot = di.Parent.Parent.FullName;
  XDocument roleModel = XDocument.Load(Path.Combine(roleRoot, "RoleModel.xml"));
  var propertyElements = roleModel.Descendants(srvDefNs + "Property");
  XElement sitePhysicalPathPropertyElement = propertyElements.Attributes("name").Where(nameAttr => nameAttr.Value == "SitePhysicalPath").Single().Parent;
  string pathToWebsite = sitePhysicalPathPropertyElement.Attribute("value").Value;
Run Code Online (Sandbox Code Playgroud)

如何以在开发和Azure上工作的方式从RoleEntryPoint.OnStart()获取WebRole站点根路径?

maw*_*tex 12

这似乎适用于dev和Windows Azure:

private IEnumerable<string> WebSiteDirectories
{
    get
    {
        string roleRootDir = Environment.GetEnvironmentVariable("RdRoleRoot");
        string appRootDir = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);

        XDocument roleModelDoc = XDocument.Load(Path.Combine(roleRootDir, "RoleModel.xml"));
        var siteElements = roleModelDoc.Root.Element(_roleModelNs + "Sites").Elements(_roleModelNs + "Site");

        return
            from siteElement in siteElements
            where siteElement.Attribute("name") != null
                    && siteElement.Attribute("name").Value == "Web"
                    && siteElement.Attribute("physicalDirectory") != null
            select Path.Combine(appRootDir, siteElement.Attribute("physicalDirectory").Value);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果有人使用它来操作ASP.NET应用程序中的文件,您应该知道RoleEntryPoint.OnStart()写入的文件将具有阻止ASP.NET应用程序更新它们的ACL设置.

如果您需要从ASP.NET写入此类文件,此代码将显示如何更改文件权限,以便可以:

SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
IdentityReference act = sid.Translate(typeof(NTAccount));
FileSecurity sec = File.GetAccessControl(testFilePath);
sec.AddAccessRule(new FileSystemAccessRule(act, FileSystemRights.FullControl, AccessControlType.Allow));
File.SetAccessControl(testFilePath, sec);
Run Code Online (Sandbox Code Playgroud)