65.9K
CodeProject 正在变化。 阅读更多。
Home

Azure HTTP Functions 示例 - CUSIP 验证

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (1投票)

2017 年 8 月 17 日

CPOL

2分钟阅读

viewsIcon

7772

无服务器 Azure 函数简介

引言

Azure 函数是一种完全无服务器的方式,可以通过云为您的应用程序提供常用功能,而无需管理虚拟机或配置等开销。您只需为实际执行时间付费,所有扩展都将为您处理。

背景

此示例是一项通常在金融系统中使用的功能,用于验证 CUSIP,这是一种用于唯一标识在北美市场交易的金融证券的特殊 9 位数字标识符。此数字的最后一位是用于检查 CUSIP 是否有效的校验和数字。

由于此验证是幂等的且不需要外部存储,因此它是 Azure 函数的理想选择。

创建新的 Azure 函数

您在 Azure 门户的“应用服务”部分中创建新函数。

当您选择此按钮时,快速入门屏幕允许您选择一种语言和启动模板。

对于此示例,选择了用 C# 编写的 API。

 

函数包装器 (run.csx)

模板会创建一个处理连接的包装器,然后您需要编写接受输入并返回适当 HTTP 响应的代码。

#load "cusip.csx"

using System.Net;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info("C# HTTP CUSIP validation function");

    // parse query parameter to get the cusip passed in
    string cusip = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "cusip", true) == 0)
        .Value;

    // Get request body
    dynamic data = await req.Content.ReadAsAsync<object>();

    // Set name to query string or body data
    cusip = cusip ?? data?.cusip;

    if (IsValidCusip(cusip))
    {
        log.Info("Valid CUSIP : " + cusip);
       return req.CreateResponse(HttpStatusCode.OK, "true");
    }
    else
    {
       log.Info("Invalid CUSIP : " + cusip);
       return req.CreateResponse(HttpStatusCode.OK, "false");
    }
}

在这种情况下,我们只想在 CUSIP 有效时返回“true”,如果无效则返回“false”。

自定义(共享)函数

如果您有希望在不同的 Azure 函数之间共享的功能,可以将它放在一个单独的代码文件中,然后在 Azure 函数中引用它。您需要使用 #load 命令在函数包装器中引用它。

public static bool IsValidCusip(string cusip)
{
    // CUSIP must not be empty
    if (string.IsNullOrWhiteSpace(cusip))
    {
        return false;
    }

    // CUSIP must be 9 digits
    if (cusip.Length == 9)
    {
        int checkDigit = getExpectedCheckDigit(cusip);
        int expectedCheckDigit = (int)Char.GetNumericValue(cusip[8]);
        return (checkDigit == expectedCheckDigit);
    }

    return false;
}

触发 Azure 函数

要运行 Azure 函数,您可以使用以下形式的 URL:https://{function app name}.azurewebsites.net/api/{function name},并将任何参数通过查询字符串或请求正文传递 - 例如,您可以使用 https://fundadmin.azurewebsites.net/api/CUSIPValidation?cusip=00846U101

历史

  • 2017 年 8 月 17 日 - 首次版本
Azure HTTP 函数示例 - CUSIP 验证 - CodeProject - 代码之家
© . All rights reserved.