如何在 .NET Core 函数应用中处理 POST JSON 请求?

huangapple go评论51阅读模式
英文:

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(&quot;command&quot;)]
    public async Task&lt;IActionAsynResult&gt; HandleCommand(
        [HttpTrigger(AuthorizationLevel.Anonymous, &quot;POST&quot;, Route = &quot;command&quot;)]
        HttpRequest request,
        ILogger logger)
    {
        using (StreamReader streamReader = new StreamReader(request.Body))
        {
            var requestBody = await streamReader.ReadToEndAsync();
            var command = JsonConvert.DeserializeObject&lt;Command&gt;(requestBody);
        }

        return new OkObjectResult(new List&lt;MyType&gt;());
    }

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(&quot;command&quot;)]
public async Task&lt;IActionAsynResult&gt; HandleCommand(
    [HttpTrigger(AuthorizationLevel.Anonymous, &quot;POST&quot;, Route = &quot;command&quot;)]
    Command command, ILogger logger)
{
    return new OkObjectResult(new List&lt;MyType&gt;());
}

Source

huangapple
  • 本文由 发表于 2023年4月4日 16:43:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75927271.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定