コード例 #1
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "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));
            }

            ShortUrlEntity input = await req.Content.ReadAsAsync <ShortUrlEntity>();

            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://'."));
            }

            ShortUrlEntity result;
            var            config = new ConfigurationBuilder()
                                    .SetBasePath(context.FunctionAppDirectory)
                                    .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                                    .AddEnvironmentVariables()
                                    .Build();

            StorageTableHelper stgHelper = new StorageTableHelper(config["UrlsDataStorage"]);

            try
            {
                result = await stgHelper.UpdateShortUrlEntity(input);

                var host = req.RequestUri.GetLeftPart(UriPartial.Authority);
                result.ShortUrl = Utility.GetShortUrl(host, result.RowKey);
            }
            catch (Exception ex)
            {
                log.LogError(ex, "An unexpected error was encountered.");
                return(req.CreateResponse(HttpStatusCode.BadRequest, ex));
            }

            return(req.CreateResponse(HttpStatusCode.OK, result));
        }
コード例 #2
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "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));
            }

            ShortUrlEntity input = await req.Content.ReadAsAsync <ShortUrlEntity>();

            if (input == null)
            {
                return(req.CreateResponse(HttpStatusCode.NotFound));
            }

            if (!Regex.IsMatch(input.Url, @"https:\/\/[a-z]*.*clashofstreamers.tv"))
            {
                return(req.CreateResponse(HttpStatusCode.NotFound));
            }

            ShortUrlEntity result;
            var            config = new ConfigurationBuilder()
                                    .SetBasePath(context.FunctionAppDirectory)
                                    .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                                    .AddEnvironmentVariables()
                                    .Build();

            StorageTableHelper stgHelper = new StorageTableHelper(config["UlsDataStorage"]);

            try
            {
                result = await stgHelper.UpdateShortUrlEntity(input);

                var host = req.RequestUri.GetLeftPart(UriPartial.Authority);
                result.ShortUrl = Utility.GetShortUrl(host, result.RowKey);
            }
            catch (Exception ex)
            {
                log.LogError(ex, "An unexpected error was encountered.");
                return(req.CreateResponse(HttpStatusCode.BadRequest, ex));
            }

            return(req.CreateResponse(HttpStatusCode.OK, result));
        }
コード例 #3
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "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;
            ShortUrlEntity input;
            ShortUrlEntity result;

            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 <ShortUrlEntity>(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"]);

                result = await stgHelper.UpdateShortUrlEntity(input);

                var host = string.IsNullOrEmpty(config["customDomain"]) ? req.Host.Host: config["customDomain"].ToString();
                result.ShortUrl = Utility.GetShortUrl(host, result.RowKey);
            }
            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));
        }