从Azure功能发送请求时出错

时间:2017-01-11 17:08:08

标签: azure asp.net-web-api azure-functions

我已经配置了 Azure功能,用于侦听到 Azure Service Bus 的传入消息。我可以毫无问题地收到邮件。但是当我尝试将请求路由到另一个服务进行处理时,我收到一条错误,指出POST数据为空。

public static void Run(BrokeredMessage message, TraceWriter log)
{
  log.Info($"C# ServiceBus queue trigger function processed message: {message.MessageId}");

  if (message != null)
  {
    //MessageObjectEntity is a custom object
    Common.Entities.MessageObjectEntity messageObject = message?.GetBody<Common.Entities.MessageObjectEntity>();
    string msgType = messageObject?.MessageType;
    var msgContent = messageObject?.MessageContent; // MessageContent is of type object to allow any object to be sent

    using (var client = new HttpClient())
    {
        string url = $"http://mycompany.azurewebsites.net/api/routingtasks?formname={msgType}";
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(subscriber, token);
        HttpContent content = new StringContent((string)msgContent, Encoding.UTF8, "application/json");
        var response = client.PostAsync(new Uri(url), content); // at this point content is valid

        // I am getting a BadRequest returned here as the target service has not received the POST data
        // that was sent in via the content variable
    }

    log.Info("Completing message.");
}

看来,尽管发送了变量 content 中发送的POST数据,但仍未收到。

更新

当我在记录器中检查发送到我的Azure功能的JSON时,它看起来像这样。

{"FormName":"UpdateMileage","FormData":[{"Key":"enteredmileage","Value":100},{"Key":"todaysdate","Value":"01/01/2017"}],"Profile":{"EmailAddress":"unittest@mycompany.co.uk","ID":9999999}}

哪个不起作用。

但是,如果我从Azure函数硬编码以下JSON,它可以正常工作(需要双引号来转义反斜杠)。

"\"{\\\"FormName\\\":\\\"UpdateMileage\\\","\\\"FormData\\\":"[{\\\"Key\\\":\\\"enteredmileage\\\",\\\"Value\\\":100},"{\\\"Key\\\":\\\"todaysdate\\\",\\\"Value\\\":\\\"01/01/2017\\\"}],"\\\"Profile\\\":"{\\\"EmailAddress\\\":\\\"unittest@mycompany.co.uk\\\","\\\"ID\\\":9999999}}\""

因此问题似乎是从我的Azure功能发送的JSON格式,但我不知道如何将我的JSON转换为这种格式。

1 个答案:

答案 0 :(得分:0)

问题是由于我将JSON发送到ASP.NET Web API服务,但是将其作为字符串类型发送。这是错的。

以下article解释了将JSON数据作为POST请求发送时的正确方法。