如何以编程方式在azure网站中创建虚拟应用程序和目录

时间:2015-09-23 12:18:10

标签: c# azure

我们使用Windows Azure网站管理库并使用C#代码以编程方式创建Web应用程序,但我们无法在Web应用程序内创建虚拟目录。请帮我如何以编程方式在Web应用程序中创建虚拟目录 我的代码在这里

var websiteManagementClient = 
CloudContext.Clients.CreateWebSiteManagementClient(Credentials);


var webSpaces = websiteManagementClient.WebSpaces.List();
var webSpace = webSpaces.FirstOrDefault(x => x.GeoRegion == "South Central US");
if (webSpace == null)
{
    throw new Exception(string.Format("No webspace for region {0} found", "South Central US"));
}

var webHostingPlans = websiteManagementClient.WebHostingPlans.List(webSpace.Name);
var webHostingPlan = webHostingPlans.FirstOrDefault();
if (webHostingPlan == null)
{
    throw new Exception(string.Format("No webhostingplan found"));
}

try
{
    var website = websiteManagementClient.WebSites.Get(webSpace.Name, "MyAzureTestSite", null);

    if (website != null)
    {
        throw new Exception(string.Format("The website {0} already exists", ""));
    }
}
catch (Exception)
{
}

var websiteCreateParams = new WebSiteCreateParameters();
websiteCreateParams.Name = "MyAzureTestSite";
websiteCreateParams.ServerFarm = webHostingPlan.Name;
websiteManagementClient.WebSites.Create(webSpace.Name, websiteCreateParams);

1 个答案:

答案 0 :(得分:1)

起初我尝试在Azure SDK的帮助下创建虚拟目录,但没有成功。最后,我使用http请求来创建它。

如果您可以使用此方法,可以在我的博客上查看。

http://kapiltak.blogspot.in/2015/10/how-to-create-virtual-application-in.html

using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Threading;

namespace ConsoleApplication1
{
    public class Azure
    {
        private string loginpath = "https://login.windows.net/{0}";
        private string apiEndpoint = "https://management.azure.com/";

        //Fill these up
        private string webSiteName = "{your webSiteName}";
        private string webSpaceName = "Default-Web-SoutheastAsia"; //Insert your webSpaceName here
        private string tenantId = "{your tenantId}";
        private string clientId = "{your client Id}";
        private string subscriptionId = "{your subscription Id}";

        //Not needed to set in console app because a function is called to get the token
        //string token = "";

        public void CreateVD(string name)
        {
            try
            {
                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(String.Format(@"https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Web/sites/{2}/config/web?api-version=2015-08-01",subscriptionId,webSpaceName,webSiteName));
                request.Headers.Add("x-ms-version", "2013-03-01");
                request.ContentType = "application/json";
                var token = GetAuthorizationHeader();
                request.Headers.Add("Authorization", "Bearer" + " " + token);

                System.Net.WebResponse response = request.GetResponse();

                string data = "";
                using (System.IO.Stream stream = response.GetResponseStream())
                {
                    System.IO.StreamReader sr = new System.IO.StreamReader(stream);
                    data = sr.ReadToEnd();
                    sr.Close();
                    stream.Close();
                    Console.WriteLine("data found");
                }

                if (data == "")
                {
                    Console.WriteLine("Error in collecting data");
                    return;
                }

                string path = name, directory = name;
                data = data.Replace("virtualApplications\":[", "virtualApplications\":[{\"virtualPath\":\"/" + path + "\",\"physicalPath\":\"site\\\\wwwroot\\\\" + directory + "\",\"preloadEnabled\":false,\"virtualDirectories\":null},");
                request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(String.Format(@"https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Web/sites/{2}/config/web?api-version=2015-08-01",subscriptionId,webSpaceName,webSiteName));
                request.Headers.Add("x-ms-version", "2013-03-01");
                request.ContentType = "application/json";
                request.AllowWriteStreamBuffering = false;
                request.Accept = "Accept=application/json";
                request.SendChunked = false;
                request.Headers.Add("Authorization", "Bearer" + " " + token);
                request.ContentLength = data.Length;
                request.Method = "PUT";

                System.IO.StreamWriter sw = new System.IO.StreamWriter(request.GetRequestStream());
                sw.Write(data);
                sw.Close();

                response = request.GetResponse();

                using (System.IO.Stream stream = response.GetResponseStream())
                {
                    data = (new System.IO.StreamReader(stream)).ReadToEnd();
                    Console.WriteLine("DONE");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
        }

        private string GetAuthorizationHeader()
        {
            AuthenticationResult result = null;

            var context = new AuthenticationContext(string.Format(loginpath, tenantId));

            var thread = new Thread(() =>
            {
                result = context.AcquireToken(apiEndpoint, clientId, new Uri(redirectUri));
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Name = "AquireTokenThread";
            thread.Start();
            thread.Join();

            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the JWT token");
            }

            string token = result.AccessToken;
            return token;
        }
    }
}

此代码可用于从网站本身创建虚拟目录,但您不能使用" GetAuthorizationHeader()"获取令牌的方法。相反,您可以通过运行控制台应用程序一次获取令牌,并使用断点来获取字符串值。在代码中使用此值并删除" GetAuthorizationHeader()"方法