1

我有一个非常简单的 Azure HTTP 触发函数,它接收POST数据:

{
    "symbols": ["Azure1", "Azure2", "Azure3"]
}

我的 Azure 功能是:

#r "Newtonsoft.Json"
using System.Net;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    // parse query parameter
    string symbols = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "symbol", true) == 0)
        .Value;

    // Get request body
    dynamic data = await req.Content.ReadAsAsync<object>();

    // Set name to query string or body data
    symbols = symbols ?? data?.symbols;

    return symbols == null
        ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
        : req.CreateResponse(HttpStatusCode.OK, symbols, JsonMediaTypeFormatter.DefaultMediaType);
}

但是,我收到带有错误消息的 500 响应:Cannot implicitly convert type 'Newtonsoft.Json.Linq.JArray' to 'string'. An explicit conversion exists (are you missing a cast?).

有谁看到我在这里可能出错的地方?我的期望是函数响应是:

["Azure1", "Azure2", "Azure3"]
4

1 回答 1

3

这个错误是有道理的。您声明symbols为 a string,但稍后您将其分配data?.symbols给它,这是一个数组。因此消息Cannot implicitly convert type 'Newtonsoft.Json.Linq.JArray' to 'string'

除非您想支持通过查询字符串传递数据,否则您应该摆脱该查询字符串逻辑。例如试试这个:

#r "Newtonsoft.Json"
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using Newtonsoft.Json.Linq;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    dynamic data = await req.Content.ReadAsAsync<object>();
    JArray symbols = data?.symbols;

    return symbols == null
        ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass symbols in the body")
        : req.CreateResponse(HttpStatusCode.OK, symbols, JsonMediaTypeFormatter.DefaultMediaType);
}
于 2017-11-28T03:33:54.963 回答