Azure功能中的HTTP修补程序

时间:2019-02-17 08:56:24

标签: c# rest azure azure-functions

我正在寻找一种在Azure函数中实现正确的HTTP路径的方法。我发现了一些示例,这些示例检查每个属性的null并将其添加到PATCH的实体中。我发现这并不理想,而只是一种解决方法。我发现HTTP触发功能(v2)的唯一签名是

public async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "HTTP VERB", Route = "")] HttpRequest req,
     ILogger log)
    {
    }

相反,我需要传递“ JsonPatchDocument ”,并且客户端将能够按如下所示传递PATCH文档,

public async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "PATCH", Route = "")] **JsonPatchDocument<Customer> patch**,
 ILogger log)
{
}

PATCH /api/customer
[
    {
      "op": "replace",
      "path": "/firstname",
      "value": "Vijay"
    },
    {
      "op": "replace",
      "path": "/email",
      "value": "example@example.com"
    },
]

,以便我可以使用“ patch.ApplyTo()”对属性进行路径设置。可以使用天蓝色函数吗?

1 个答案:

答案 0 :(得分:0)

我为此找到了解决方案。我无法将“ JsonPatchDcument” 类型传递给Azure函数,但可以将请求正文解析为JsonPatchDocument,如下所示,

FunctionName("PatchInstitute")]
    public async Task<IActionResult> PatchInstitute(
        [HttpTrigger(AuthorizationLevel.Anonymous, "patch", Route = ApiConstants.BaseRoute + "/institute/{instituteId}")] HttpRequest req,
        ILogger log, [Inject]IInstituteValidator instituteValidator, int instituteId, [Inject] IInstituteProvider instituteProvider)
    {
        try
        {
           //get existing record with Id here
            var instituteDto = instituteProvider.GetInstitueProfileById(instituteId);



            using (StreamReader streamReader = new StreamReader(req.Body))
            {
                var requestBody = await streamReader.ReadToEndAsync();

                //Deserialize bosy to strongly typed JsonPatchDocument
                JsonPatchDocument<InstituteDto> jsonPatchDocument = JsonConvert.DeserializeObject<JsonPatchDocument<InstituteDto>>(requestBody);

                //Apply patch here
                jsonPatchDocument.ApplyTo(instituteDto);

                //Apply the change
                instituteProvider.UpdateInstitute(instituteDto);

            }

            return new OkResult();

        }
        catch (Exception ex)
        {
            log.LogError(ex.ToString());
           // return Generic Exception here
        }
    }

从客户端传递的JsonPathDocument如下所示,

[
    {
      "op": "replace",
      "path": "/isActive",
      "value": "true"
    }
]

您可以在此处传递任何要更新(补丁)的字段