public static async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, ILogger log, ExecutionContext context) { log.LogInformation($"C# HTTP trigger function processed this request: {req}"); // Validation of the inputs if (req == null) { return(req.CreateResponse(HttpStatusCode.NotFound)); } ShortRequest input = await req.Content.ReadAsAsync <ShortRequest>(); if (input == null) { return(req.CreateResponse(HttpStatusCode.NotFound)); } // If the Url parameter only contains whitespaces or is empty return with BadRequest. if (string.IsNullOrWhiteSpace(input.Url)) { return(req.CreateErrorResponse(HttpStatusCode.BadRequest, "The url parameter can not be empty.")); } // Validates if input.url is a valid aboslute url, aka is a complete refrence to the resource, ex: http(s)://google.com if (!Uri.IsWellFormedUriString(input.Url, UriKind.Absolute)) { return(req.CreateErrorResponse(HttpStatusCode.BadRequest, $"{input.Url} is not a valid absolute Url. The Url parameter must start with 'http://' or 'http://'.")); } var result = new ShortResponse(); var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); StorageTableHelper stgHelper = new StorageTableHelper(config["UlsDataStorage"]); try { string longUrl = input.Url.Trim(); string vanity = string.IsNullOrWhiteSpace(input.Vanity) ? "" : input.Vanity.Trim(); string title = string.IsNullOrWhiteSpace(input.Title) ? "" : input.Title.Trim(); ShortUrlEntity newRow; if (!string.IsNullOrEmpty(vanity)) { newRow = new ShortUrlEntity(longUrl, vanity, title); if (await stgHelper.IfShortUrlEntityExist(newRow)) { return(req.CreateResponse(HttpStatusCode.Conflict, "This Short URL already exist.")); } } else { newRow = new ShortUrlEntity(longUrl, Utility.GetValidEndUrl(vanity), title); } await stgHelper.SaveShortUrlEntity(newRow); var host = req.RequestUri.GetLeftPart(UriPartial.Authority); log.LogInformation($"-> host = {host}"); result = new ShortResponse(host, newRow.Url, newRow.RowKey, newRow.Title); log.LogInformation("Short Url created."); } catch (Exception ex) { log.LogError(ex, "An unexpected error was encountered."); return(req.CreateResponse(HttpStatusCode.BadRequest, ex)); } return(req.CreateResponse(HttpStatusCode.OK, result)); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log, ExecutionContext context, ClaimsPrincipal principal) { log.LogInformation($"C# HTTP trigger function processed this request: {req}"); string userId = string.Empty; ShortRequest input; var result = new ShortResponse(); try { var invalidRequest = Utility.CatchUnauthorize(principal, log); if (invalidRequest != null) { return(invalidRequest); } else { userId = principal.FindFirst(ClaimTypes.GivenName).Value; log.LogInformation("Authenticated user {user}.", userId); } // Validation of the inputs if (req == null) { return(new BadRequestObjectResult(new { StatusCode = HttpStatusCode.NotFound })); } using (var reader = new StreamReader(req.Body)) { var strBody = reader.ReadToEnd(); input = JsonSerializer.Deserialize <ShortRequest>(strBody, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); if (input == null) { return(new BadRequestObjectResult(new { StatusCode = HttpStatusCode.NotFound })); } } // If the Url parameter only contains whitespaces or is empty return with BadRequest. if (string.IsNullOrWhiteSpace(input.Url)) { return(new BadRequestObjectResult(new { StatusCode = HttpStatusCode.BadRequest, Message = "The url parameter can not be empty." })); } // Validates if input.url is a valid aboslute url, aka is a complete refrence to the resource, ex: http(s)://google.com if (!Uri.IsWellFormedUriString(input.Url, UriKind.Absolute)) { return(new BadRequestObjectResult(new { StatusCode = HttpStatusCode.BadRequest, Message = $"{input.Url} is not a valid absolute Url. The Url parameter must start with 'http://' or 'http://'." })); } var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); StorageTableHelper stgHelper = new StorageTableHelper(config["UlsDataStorage"]); string longUrl = input.Url.Trim(); string vanity = string.IsNullOrWhiteSpace(input.Vanity) ? "" : input.Vanity.Trim(); string title = string.IsNullOrWhiteSpace(input.Title) ? "" : input.Title.Trim(); ShortUrlEntity newRow; if (!string.IsNullOrEmpty(vanity)) { newRow = new ShortUrlEntity(longUrl, vanity, title, input.Schedules); if (await stgHelper.IfShortUrlEntityExist(newRow)) { return(new ConflictObjectResult(new{ Message = "This Short URL already exist." })); } } else { newRow = new ShortUrlEntity(longUrl, await Utility.GetValidEndUrl(vanity, stgHelper), title, input.Schedules); } await stgHelper.SaveShortUrlEntity(newRow); var host = string.IsNullOrEmpty(config["customDomain"]) ? req.Host.Host: config["customDomain"].ToString(); result = new ShortResponse(host, newRow.Url, newRow.RowKey, newRow.Title); log.LogInformation("Short Url created."); } catch (Exception ex) { log.LogError(ex, "An unexpected error was encountered."); return(new BadRequestObjectResult(new { message = ex.Message, StatusCode = HttpStatusCode.BadRequest })); } return(new OkObjectResult(result)); }
public static async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, ILogger log, ExecutionContext context) { log.LogInformation($"C# HTTP trigger function processed this request: {req}"); // Validation of the inputs if (req == null) { return(req.CreateResponse(HttpStatusCode.NotFound)); } ShortRequest input = await req.Content.ReadAsAsync <ShortRequest>(); if (input == null) { return(req.CreateResponse(HttpStatusCode.NotFound)); } var result = new ShortResponse(); var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); StorageTableHelper stgHelper = new StorageTableHelper(config["UlsDataStorage"]); try { string longUrl = input.Url.Trim(); string vanity = input.Vanity.Trim(); ShortUrlEntity newRow; if (!string.IsNullOrEmpty(vanity)) { newRow = new ShortUrlEntity(longUrl, vanity); if (await stgHelper.IfShortUrlEntityExist(newRow)) { return(req.CreateResponse(HttpStatusCode.Conflict, "This Short URL already exist.")); } } else { newRow = new ShortUrlEntity(longUrl, await Utility.GetValidEndUrl(vanity, stgHelper)); } await stgHelper.SaveShortUrlEntity(newRow); var host = req.RequestUri.GetLeftPart(UriPartial.Authority); log.LogInformation($"-> host = {host}"); result = new ShortResponse(host, newRow.Url, newRow.RowKey); log.LogInformation("Short Url created."); } catch (Exception ex) { log.LogError(ex, "An unexpected error was encountered."); return(req.CreateResponse(HttpStatusCode.BadRequest, ex)); } return(req.CreateResponse(HttpStatusCode.OK, result)); }