我正在寻找一种在 Azure 函数中实现正确 HTTP 路径的方法。我找到了一些示例,这些示例检查每个属性的 null 并将其添加到要修补的实体中。我发现这并不理想,只是一种解决方法。我发现的 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": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d6b3aeb7bba6bab396b3aeb7bba6bab3f8b5b9bb" rel="noreferrer noopener nofollow">[email protected]</a>"
},
]
这样我就可以使用“patch.ApplyTo()”来路径属性。可以在azure函数中执行吗?
最佳答案
我找到了解决这个问题的方法。我无法将 "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"
}
]
在这里您可以传递任何要更新的字段(补丁)
关于c# - azure 函数中的 HTTP 补丁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54731597/