简体   繁体   English

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

[英]How to create a virtual application and directories in azure website programmatically

We use Windows Azure website management library and create a web app programmatically by using C# code but we cannot create a virtual directory inside a web app. 我们使用Windows Azure网站管理库,并使用C#代码以编程方式创建Web应用程序,但是我们无法在Web应用程序内部创建虚拟目录。 please help me how to create virtual directory inside a web app programmatically My Code here 请帮助我如何在网络应用程序内以编程方式在我的代码中创建虚拟目录

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);

At first I tried to create virtual directory with the help of Azure SDK but was not successful. 最初,我尝试在Azure SDK的帮助下创建虚拟目录,但未成功。 Finally, I used http request to create it. 最后,我使用http请求创建了它。

If you can use this method, you can check it out on my blog. 如果可以使用此方法,则可以在我的博客上查看。

http://kapiltak.blogspot.in/2015/10/how-to-create-virtual-application-in.html 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;
        }
    }
}

This code can be used to create virtual directory from website itself but you cannot use "GetAuthorizationHeader()" method to get the token. 该代码可用于从网站本身创建虚拟目录,但是您不能使用“ GetAuthorizationHeader()”方法来获取令牌。 Instead you can get the token by running the console app once and use a breakpoint to get the string value. 相反,您可以通过运行控制台应用程序一次来获取令牌,并使用断点获取字符串值。 Use this value in the code and remove the "GetAuthorizationHeader()" method. 在代码中使用此值,然后删除“ GetAuthorizationHeader()”方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 以编程方式向 Azure WebApp 添加新的虚拟目录 - Add new Virtual Directories to an Azure WebApp programmatically 以编程方式为网站创建虚拟目录-Web应用程序 - create a virtual directory for a website programmatically- web application 使用Azure API,如何列出虚拟目录并将其添加到网站? - Using the Azure API, how do I list and add virtual directories to a website? 如何以编程方式创建Azure网站和SQL数据库? - How do I create an Azure Website and SQL Database programmatically? IIS 6.0以编程方式 - 创建虚拟目录时出现问题而不将其设置为应用程序 - IIS 6.0 programmatically - Problem creating virtual directories AND not setting it as a Application 如何以编程方式禁用IIS6应用程序(不是虚拟目录) - How do I programmatically disable IIS6 Applications (not virtual directories) 如何判断Azure容器是否具有虚拟文件夹/目录? - How to tell if Azure Container has Virtual folders/directories? 使用C#代码或.net以编程方式在Windows Azure中创建虚拟机 - Create a virtual machine in windows azure programmatically with C# code or .net 在IIS 7.5中创建虚拟目录 - Create Virtual Directories in IIS 7.5 在IIS 6.0中的子目录中创建虚拟目录(以编程方式) - Creating virtual directories in sub directories in IIS 6.0 (programmatically)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM