-
Notifications
You must be signed in to change notification settings - Fork 522
/
UrlRedirect.cs
61 lines (52 loc) · 2.14 KB
/
UrlRedirect.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using System;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using System.Net;
using System.Net.Http;
using Cloud5mins.domain;
using Microsoft.Extensions.Configuration;
namespace Cloud5mins.Function
{
public static class UrlRedirect
{
[FunctionName("UrlRedirect")]
public static async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "UrlRedirect/{shortUrl}")] HttpRequestMessage req,
string shortUrl,
ExecutionContext context,
ILogger log)
{
log.LogInformation($"C# HTTP trigger function processed for Url: {shortUrl}");
string redirectUrl = "https://azure.com";
if (!String.IsNullOrWhiteSpace(shortUrl))
{
var config = new ConfigurationBuilder()
.SetBasePath(context.FunctionAppDirectory)
.AddJsonFile("settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
redirectUrl = config["defaultRedirectUrl"];
StorageTableHelper stgHelper = new StorageTableHelper(config["UlsDataStorage"]);
var tempUrl = new ShortUrlEntity(string.Empty, shortUrl);
var newUrl = await stgHelper.GetShortUrlEntity(tempUrl);
if (newUrl != null)
{
//log.LogInformation($"Found it: {newUrl.Url}");
newUrl.Clicks++;
stgHelper.SaveClickStatsEntity(new ClickStatsEntity(newUrl.RowKey));
await stgHelper.SaveShortUrlEntity(newUrl);
redirectUrl = WebUtility.UrlDecode(newUrl.ActiveUrl);
}
}
else
{
log.LogInformation("Bad Link, resorting to fallback.");
}
var res = req.CreateResponse(HttpStatusCode.Redirect);
res.Headers.Add("Location", redirectUrl);
return res;
}
}
}