dav*_*rgh 25 c# post azure visual-studio azure-functions
我正在尝试使用简单的Azure功能来了解它.将有3个功能:
我已经能够完成第一个和第三个.但我无法通过POST传递参数.我找了一些例子,但是我无法成功地运行它们.客户端应用程序是Windows窗体.
谁能告诉我一个例子,如何通过POST将参数传递给函数以及如何阅读它们?
提前致谢
编辑:
这是通过GET传递参数的代码(这很好):
private void button2_Click(object sender, EventArgs e)
{
string cadena = lsql1.Text + "?notas=" + tNotas.Text;
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(cadena);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
if (res.StatusCode == HttpStatusCode.OK)
{
MessageBox.Show("Grabado");
}
else
{
MessageBox.Show(res.StatusDescription);
}
}catch (WebException ex)
{
using (Stream s = ex.Response.GetResponseStream())
{
StreamReader sr = new StreamReader(s);
string text = sr.ReadToEnd();
text = text.Substring(1, text.Length - 2);
sr.Close();
text = text.Replace("\\", "");
text = "{" + text + "}";
Error mensajeError = JsonConvert.DeserializeObject<Error>(text);
MessageBox.Show(mensajeError.ExceptionMessage);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是接收它并执行插入的代码(这也是有效的):
[FunctionName("sql1")]
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
try
{
log.Info("C# HTTP trigger function processed a request.");
var cnnString = "Server=SERVIDOR;Database=base_prueba;User ID =azure;Password=0000;Trusted_Connection=False;Encrypt=False;";
using (SqlConnection connection = new SqlConnection(cnnString))
{
connection.Open();
SqlCommand cmd = connection.CreateCommand();
DateTime fecha = DateTime.Today;
string notas = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "notas", true) == 0)
.Value;
// insert a log to the database
cmd.CommandText = "INSERT INTO Prueba_Azure (fecha, notas) VALUES ('" + fecha.ToString() + "', '" + notas + "')";
cmd.ExecuteNonQuery();
}
// Get request body
dynamic data = await req.Content.ReadAsAsync<object>();
return name == req.CreateResponse(HttpStatusCode.OK, "Done");
}
catch (Exception ex)
{
HttpResponseMessage res = req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
return res;
}
}
Run Code Online (Sandbox Code Playgroud)
我正在寻找的是POST
Amo*_*mor 29
要从请求正文中获取请求内容(发布请求),您可以使用req.Content.ReadAsAsync方法.这是代码示例.
样品申请机构.
{
"name": "Azure"
}
Run Code Online (Sandbox Code Playgroud)
定义一个类来反序列化后期数据.
public class PostData
{
public string name { get;set; }
}
Run Code Online (Sandbox Code Playgroud)
获取发布数据并显示它.
PostData data = await req.Content.ReadAsAsync<PostData>();
log.Info("name:" + data.name);
Run Code Online (Sandbox Code Playgroud)
客户端代码发送帖子请求.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("function-url");
req.Method = "POST";
req.ContentType = "application/json";
Stream stream = req.GetRequestStream();
string json = "{\"name\": \"Azure\" }";
byte[] buffer = Encoding.UTF8.GetBytes(json);
stream.Write(buffer,0, buffer.Length);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
Run Code Online (Sandbox Code Playgroud)
All*_*ang 19
万一谷歌把你带到这里,这是2019年3月的事情:
public static async void Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]
HttpRequest req,
ILogger log)
{
var content = await new StreamReader(req.Body).ReadToEndAsync();
MyClass myClass = JsonConvert.DeserializeObject<MyClass>(content);
}
Run Code Online (Sandbox Code Playgroud)
如果您正在使用System.Text.Json,则可以在一行中读取 POST 数据:
public static async Task Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]
HttpRequest req,
ILogger log)
{
MyClass myClass = await JsonSerializer.DeserializeAsync<MyClass>(req.Body);
}
Run Code Online (Sandbox Code Playgroud)
如果您正在使用Newtonsoft.Json,请参阅Allen Zhang 的回答。
要将参数作为 POST 请求传递,您需要执行以下操作:
制作你需要传递的参数的 Json 模型,例如:
{"UserProfile":{ "UserId":"xyz1","FirstName":"Tom","LastName":"Hank" }}
Run Code Online (Sandbox Code Playgroud)使用像 POSTMAN 这样的客户端发布您的数据模型
现在您将在HttpRequestMessage正文中获取发布的内容,示例代码如下:
[FunctionName("TestPost")]
public static HttpResponseMessage POST([HttpTrigger(AuthorizationLevel.Function, "put", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
{
try
{
//create redis connection and database
var RedisConnection = RedisConnectionFactory.GetConnection();
var serializer = new NewtonsoftSerializer();
var cacheClient = new StackExchangeRedisCacheClient(RedisConnection, serializer);
//read json object from request body
var content = req.Content;
string JsonContent = content.ReadAsStringAsync().Result;
var expirytime = DateTime.Now.AddHours(Convert.ToInt16(ConfigurationSettings.AppSettings["ExpiresAt"]));
SessionModel ObjModel = JsonConvert.DeserializeObject<SessionModel>(JsonContent);
bool added = cacheClient.Add("RedisKey", ObjModel, expirytime); //store to cache
return req.CreateResponse(HttpStatusCode.OK, "RedisKey");
}
catch (Exception ex)
{
return req.CreateErrorResponse(HttpStatusCode.InternalServerError, "an error has occured");
}
}
Run Code Online (Sandbox Code Playgroud)您可以只提供自定义数据类作为参数的参数HttpTrigger。这样你就不必自己搞乱 json 反序列化:
public async Task<IActionResult> UpdateAccount(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "api/v1/accounts/{id:guid}")]
SomeData someData, // <----- Post body ends up here automatically
HttpRequest req,
Guid id,
ILogger log)
{
log.LogInformation ("Got POST with " + someData.Foo);
}
public class SomeData
{
public string Foo { get; set; } = null!;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36950 次 |
| 最近记录: |