使用Cloudflare CF-IPCountry选择要从中获取图像的文件夹

时间:2018-08-15 18:17:55

标签: c# asp.net cloudflare

我目前正在尝试学习C#,这对我来说有点陌生,因此,如果我要问一些基本的问题,我深表歉意。

我想使用Cloudflares GEO IP,它可以反馈国家代码,例如美国,GB,AU。

根据给出的国家/地区,我想选择其他目录以随机选择图像。

例如,如果CF表示GB,我希望它从/ img / gb /中选择随机图像。 就像this script一样,只是在C#中。

到目前为止,我已经写了这本书,可以在一个文件夹中使用,但是我一直停留在这一部分。

public class getimage : IHttpHandler
{
    public void ProcessRequest (HttpContext context)
    {
        // Set a default for images
        string imgdirectory = "/img";

        // check if a directory has been given as a source for images
        if (context.Request.QueryString["d"] != null)
        {
            imgdirectory = context.Request.QueryString["d"];
        }

        // read in all the images into an array
        string[] imgarray = Directory.GetFiles(HttpContext.Current.Server.MapPath(imgdirectory), "*.jpg");

        // generate a radom number upto the total number of images
        Random random = new Random();
        int randomNumber = random.Next(0, imgarray.Length);

        // read in the file
        byte[] imageBytes =File.ReadAllBytes(imgarray[randomNumber]);

        // output the image 
        using (MemoryStream ms = new MemoryStream(imageBytes))
        {
            context.Response.ContentType = "image/jpg";
            ms.WriteTo(context.Response.OutputStream);
        }
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

要回答我自己的问题:

    protected void Page_Load(object sender, EventArgs e)
{
    string filename = "";
    if (Request.Headers.AllKeys.Contains("CF-IPCountry"))
    {
        string countrycode = Request.Headers["CF-IPCountry"].ToString();
        if (Directory.Exists(Server.MapPath("~/img/" + countrycode)))
        {
            string[] files = Directory.GetFiles(Server.MapPath("~/img/" + countrycode + "/"), "*.jpg");
            Random _r = new Random();
            int randomimage = _r.Next(files.Length);
            filename = "/img/" + countrycode + "/" + Path.GetFileName(files[randomimage]);
        }

    }
    if (filename.Length == 0)
    {
        string[] files = Directory.GetFiles(Server.MapPath("~/img/none/"), "*.jpg");
        Random _r = new Random();
        int randomimage = _r.Next(files.Length);
        filename = "/img/none/" + Path.GetFileName(files[randomimage]);
    }
    Literal1.Text = filename;
}