.NET C#基础教程第12天:Azure Functions

作者:微信公众号:【架构师老卢】
6-10 8:59
61

概述:介绍Azure Functions 是 Microsoft Azure 云平台上的无服务器应用程序,无需担心运行它的基础结构。它与 AWS 云中的 lambda 函数非常相似。学习目标使用 Visual Studio 或 Visual Studio Code 创建函数在本地运行 Azure 函数。开发人员的先决条件Visual Studio 使用经验基本了解 C# 编程语言开始添加新函数从 Visual Studio 中选择项目“Azure 函数”。选择 .Net 6 作为目标版本选择模板“HTTP Trigger”提供函数名称。选择“授权级别”作为“匿名”,这允许任何人访问您的函数终端节点。

介绍

Azure Functions 是 Microsoft Azure 云平台上的无服务器应用程序,无需担心运行它的基础结构。它与 AWS 云中的 lambda 函数非常相似。

学习目标

  • 使用 Visual Studio 或 Visual Studio Code 创建函数
  • 在本地运行 Azure 函数。

开发人员的先决条件

  • Visual Studio 使用经验
  • 基本了解 C# 编程语言

开始

添加新函数

  1. 从 Visual Studio 中选择项目“Azure 函数”。
  2. 选择 .Net 6 作为目标版本
  3. 选择模板“HTTP Trigger”
  4. 提供函数名称。
  5. 选择“授权级别”作为“匿名”,这允许任何人访问您的函数终端节点。

法典

下面的 Azure 函数返回一条消息,如下所示string

  • 如果传递,则返回一条消息?name=Hello, {name}. This HTTP triggered function executed successfully.
  • 否则,将返回常规消息This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.
public static class BasicExample
{
    [FunctionName("BasicExample")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        string name = req.Query["name"];

        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        dynamic data = JsonConvert.DeserializeObject(requestBody);
        name = name ?? data?.name;

        string responseMessage = string.IsNullOrEmpty(name)
            ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
            : $"Hello, {name}. This HTTP triggered function executed successfully.";

        return new OkObjectResult(responseMessage);
    }
}

在本地测试函数

只需按开始调试 Azure 函数,它就会打开一个控制台,该控制台将提供用于访问浏览器的 URL。F5

控制台输出

Azure Functions Core Tools
Core Tools Version:       4.0.5198 Commit hash: N/A  (64-bit)
Function Runtime Version: 4.21.1.20667

[2024-03-28T05:48:45.707Z] Found D:\Workspace\30DayChallenge.Net\AzureFunctionExample\AzureFunctionExample.csproj. Using for user secrets file configuration.

Functions:

        BasicExample: [GET,POST] http://localhost:7073/api/BasicExample

打开 URL

在浏览器中打开 URL “”,开始运行函数终结点。http://localhost:7073/api/BasicExample

从浏览器返回的响应。

This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.

添加查询参数

使用其他查询参数修改 URL,如下所示?name=Sukhpinder

http://localhost:7073/api/BasicExample?name=Sukhpinder

从浏览器返回的响应。

Hello, Sukhpinder. This HTTP triggered function executed successfully.

源代码获取:公众号回复消息【code:21108

相关代码下载地址
重要提示!:取消关注公众号后将无法再启用回复功能,不支持解封!
第一步:微信扫码关键公众号“架构师老卢”
第二步:在公众号聊天框发送code:21108,如:code:21108 获取下载地址
第三步:恭喜你,快去下载你想要的资源吧
阅读排行