Azure功能:将JSON Webhook导入SQL

时间:2017-04-08 07:51:12

标签: json azure azure-functions

我正在尝试实现以下版本:     http://sqlblog.com/blogs/davide_mauri/archive/2017/02/05/azure-functions-dapper-and-sql-server-json-to-store-form-data.aspx

然而我收到错误:

  

执行函数时出现异常:Functions.Incoming。 System.Net.Http.Formatting:没有MediaTypeFormatter可用于读取' JObject'来自媒体类型的内容' application / octet-stream'。

run.csx中的函数是:

#r "Newtonsoft.Json"

using System;
using System.Net;
using System.Net.Mail;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using Dapper;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    JObject contactFormData = await req.Content.ReadAsAsync<JObject>();

    string azureSQLConnectionString = ConfigurationManager.ConnectionStrings["sql"]?.ConnectionString;

    string payload = JsonConvert.SerializeObject(contactFormData);

    using(SqlConnection conn = new SqlConnection(azureSQLConnectionString))
    {
        conn.Execute("dbo.incomingSP", new { payload = payload }, commandType: CommandType.StoredProcedure);                
    }

    return req.CreateResponse(HttpStatusCode.OK);
}

我还有一个project.json文件:

    {
  "frameworks": {
    "net46":{
      "dependencies": {
        "Dapper": "1.42.0",
        "System.Data.SqlClient":"4.1.0",
        "Microsoft.WindowsAzure.ConfigurationManager":"3.2.1"
      }
    }
   }
}

我的测试JSON代码是:

{
    "transaction": 
    {
        "IP": "7797",
        "Time": "2017-01-01"
    }
}

1 个答案:

答案 0 :(得分:1)

根据错误消息,我认为客户端将数据作为文件发送。在这种情况下,您应该将请求内容读取为二进制,然后转换为字符串。由于您不需要在函数体内使用JSON,因此您也可以跳过反序列化/序列化并将有效负载直接传递给SQL:

var bytes = await req.Content.ReadAsByteArrayAsync(); 
var payload = System.Text.Encoding.Default.GetString(bytes); 
// Uncomment to trace your payload: 
// log.Info(payload); 

然后在您的SQL调用中使用payload