【发布时间】:2019-02-19 09:31:25
【问题描述】:
如果您能指出正确的地方或正确的想法,我将不胜感激。我已经很久没有做过 C# 了,我也不确定我在做什么了。
基本上我有一个基于 Azure 的 MSSQL 数据库,我需要从我的 iPhone 应用程序中读取数据并以 JSON 格式返回该数据。 Azure API 不允许您直接从 DB 中读取,但您可以构建一个 .Net Web API 并使用它——这就是我去的地方。
我已经完成了第一部分的工作。我可以发出一个 http 请求,Azure 响应良好。我还构建了数据库和表,并且我已经测试了所有这些并且它可以工作。我还测试了查询,它运行格式良好的 JSON。
但是,我需要将数据读取器中的数据作为 http 响应传递,我无法弄清楚那部分。附件是两个 vanilla 文件。一个发出虚拟 http 请求,另一个是 db 连接器文件。
所以简而言之,在 Function1.cs 文件中我需要从
:req.CreateResponse(HttpStatusCode.OK, "Hello" + name);到 :req.CreateResponse(HttpStatusCode.OK, );
第一个文件:Function1.cs
namespace getOutageAlerts
{ 公共静态类 Function1 { [函数名称(“函数 1”)] 公共静态异步任务运行([HttpTrigger(AuthorizationLevel.Function,“get”,“post”,Route = null)]HttpRequestMessage req,TraceWriter log) { log.Info("C# HTTP 触发函数处理了一个请求。");
// parse query parameter
string name = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
.Value;
if (name == null)
{
// Get request body
dynamic data = await req.Content.ReadAsAsync<object>();
name = data?.name;
}
return name == null
? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
**:req.CreateResponse(HttpStatusCode.OK, "Hello" + name);**
}
}
}
第二个文件:DBConnector.cs
using System;
using System.Data.SqlClient;
public class DBConnector
{
public DBConnector()
{
SqlConnection getalertsConnection = new SqlConnection("Server=tcp:xxxxxxxxx.database.windows.net,1433;Initial Catalog=mckMobileAppsDB;Persist Security Info=False;User ID=xxxxxxx;Password=xxxxxxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "SELECT Date_Created As Date, Incident_Number AS Incident, Flash_Summary AS Summary, Service, Business_Impact AS Impact, Incident_Status AS Status from OutagesMobileAppNotifications FOR JSON PATH, Root('Alerts')";
cmd.CommandType = CommandType.Text;
cmd.Connection = getalertsConnection;
getalertsConnection.Open();
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
getalertsConnection.Close();
}
}
【问题讨论】:
标签: c# json azure-sql-database