我有一个非常简单的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"]
答案 0 :(得分:2)
错误是有道理的。您将symbols
声明为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);
}