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

标签 c# azure

我们使用 Windows Azure 网站管理库并使用 C# 代码以编程方式创建 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);

最佳答案

起初我尝试借助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()”方法来获取 token 。相反,您可以通过运行控制台应用程序一次来获取 token 并使用断点来获取字符串值。在代码中使用此值并删除“GetAuthorizationHeader()”方法。

关于c# - 如何以编程方式在azure网站中创建虚拟应用程序和目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32739405/

相关文章:

windows - 如何提升在 Azure VM 上运行的远程命令的权限

c# - 如何使用 C# 获取 Azure 容器虚拟文件夹中的文件

c# - 如何在 IdentityServer 4 中使用 'refresh_token'?

c# - 这是评估 Main(string[] args) 的矫枉过正吗

c# - Xamarin iOS RegisteredForRemoteNotifications 间歇性不调用 Android 100% 的时间工作

azure - 需要为 Azure 表构建复杂的查询来计算行数

c# - InvalidCastException : Unable to cast object of type 'System.Decimal' to type 'System.String'

c# - 不用 jQuery 解析 JSON

c# - 如何在 WCF 中为客户端配置 net.tcp 绑定(bind)

Azure Web 角色未在 Azure 模拟器中启动