将Azure功能转换为WebAPI调用Azure存储

时间:2018-06-01 09:42:00

标签: azure storage azure-storage azure-functions asp.net-core-webapi

我一直在尝试将此https://blog.jeremylikness.com/build-a-serverless-link-shortener-with-analytics-faster-than-finishing-your-latte-8c094bb1df2c中的函数转换为WebAPI等效函数。这是我的webapi电话:

    [HttpPost]       
    public async Task<IActionResult> PostAsync([FromBody] ShortRequest shortRequest)
    {
        _logger.LogInformation($"ShrinkUrl api called with req: {shortRequest}");

       if(!Request.IsHttps && !Request.Host.Host.Contains("localhost"))
            return StatusCode(StatusCodes.Status400BadRequest);

        if (string.IsNullOrEmpty(shortRequest.Input))
            return StatusCode(StatusCodes.Status404NotFound);

       try
       {
            var result = new List<ShortResponse>();
            var analytics = new Analytics();

            // determine whether or not to process analytics tags
            bool tagMediums = analytics.Validate(shortRequest);

            var campaign = string.IsNullOrWhiteSpace(shortRequest.Campaign) ? DefaultCampaign : shortRequest.Campaign;
            var url = shortRequest.Input.Trim();
            var utm = analytics.TagUtm(shortRequest);
            var wt = analytics.TagWt(shortRequest);

            _logger.LogInformation($"URL: {url} Tag UTM? {utm} Tag WebTrends? {wt}");

            // get host for building short URL 
            var host = Request.Scheme + "://" + Request.Host;

            await _tableOut.CreateIfNotExistsAsync();

            if (_keyTable == null)
            {
                _logger.LogInformation($"Keytable is null, creating initial partition key of 1");

                _keyTable = new NextId
                {
                    PartitionKey = "1",
                    RowKey = "KEY",
                    Id = 1024
                };
                var keyAdd = TableOperation.Insert(_keyTable);
                await _tableOut.ExecuteAsync(keyAdd);
            }

            // strategy for getting a new code 
            string getCode() => Utility.Encode(_keyTable.Id++);

            // strategy for logging 
            void logFn(string msg) => _logger.LogInformation(msg);

            // strategy to save the key 
            async Task saveKeyAsync()
            {
                var operation = TableOperation.Replace(_keyTable);
                await _tableOut.ExecuteAsync(operation);
            }

            // strategy to insert the new short url entry
            async Task saveEntryAsync(TableEntity entry)
            {
                var operation = TableOperation.Insert(entry);
                await _tableOut.ExecuteAsync(operation);
            }

            // strategy to create a new URL and track the dependencies
            async Task saveWithTelemetryAsync(TableEntity entry)
            {
                await TrackDependencyAsync(
                    "AzureTableStorageInsert",
                    "Insert",
                    async () => await saveEntryAsync(entry),
                    () => true);
                await TrackDependencyAsync(
                    "AzureTableStorageUpdate",
                    "Update",
                    async () => await saveKeyAsync(),
                    () => true);
            }

            if (tagMediums)
            {
                // this will result in multiple entries depending on the number of 
                // mediums passed in 
                result.AddRange(await analytics.BuildAsync(
                    shortRequest,
                    Source,
                    host,
                    getCode,
                    saveWithTelemetryAsync,
                    logFn,
                    HttpUtility.ParseQueryString));
            }
            else
            {
                // no tagging, just pass-through the URL
                result.Add(await Utility.SaveUrlAsync(
                    url,
                    null,
                    host,
                    getCode,
                    logFn,
                    saveWithTelemetryAsync));
            }

            _logger.LogInformation($"Done.");
            //return req.CreateResponse(HttpStatusCode.OK, result);
        }
        catch (Exception ex)
        {
            _logger.LogError("An unexpected error was encountered.", ex);
            //return req.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
        }

        return null;
    }

这就是函数参数:

[FunctionName("ShortenUrl")]
public static async Task<HttpResponseMessage>([HttpTrigger(AuthorizationLevel.Function, "post")],HttpRequestMessage req,
        [Table(Utility.TABLE, "1", Utility.KEY, Take = 1)]NextId keyTable,
        [Table(Utility.TABLE)]CloudTable, TraceWriter log)

azure函数负责确保keyTable包含计数器中的下一个Id,但我无法弄清楚如何在webapi调用中执行相同操作。

有什么想法吗?

0 个答案:

没有答案