英文:
How to handle post json using net core function app?
问题
使用 .NET Core(Azure)函数应用程序,我想处理一个包含 JSON 对象的 POST /command 请求。编写这类处理程序的最佳方法是什么?
我的当前解决方案是使用 HttpTrigger 从请求的正文中读取 JSON 作为流,使用 StreamReader。
[FunctionName("command")]
public async Task<IActionResult> HandleCommand(
[HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "command")]
HttpRequest request,
ILogger logger)
{
using (StreamReader streamReader = new StreamReader(request.Body))
{
var requestBody = await streamReader.ReadToEndAsync();
var command = JsonConvert.DeserializeObject<Command>(requestBody);
}
return new OkObjectResult(new List<MyType>());
}
这是否是最佳方法?
英文:
Using .net core (azure) function app I want to handle a POST /command request that contains a json object in the body of the request.
What is the best approach for writing these type of handlers?
My current solution is to use an HttpTrigger that reads json from the body as a stream using a streamreader.
[FunctionName("command")]
public async Task<IActionAsynResult> HandleCommand(
[HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "command")]
HttpRequest request,
ILogger logger)
{
using (StreamReader streamReader = new StreamReader(request.Body))
{
var requestBody = await streamReader.ReadToEndAsync();
var command = JsonConvert.DeserializeObject<Command>(requestBody);
}
return new OkObjectResult(new List<MyType>());
}
Is this the best approach?
答案1
得分: 1
如果您不需要自定义处理JSON序列化,可以直接将Command
对象传递给您的函数,而不是HttpRequest
。
[FunctionName("command")]
public async Task<IActionAsynResult> HandleCommand(
[HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "command")]
Command command, ILogger logger)
{
return new OkObjectResult(new List<MyType>());
}
英文:
If you don't need custom handling of the JSON serialization, you can directly have the Command
object passed into your Function, instead of HttpRequest
.
[FunctionName("command")]
public async Task<IActionAsynResult> HandleCommand(
[HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "command")]
Command command, ILogger logger)
{
return new OkObjectResult(new List<MyType>());
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论