我正在尝试在 Azure 函数中获取表单数据。
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
NameValueCollection col = req.Content.ReadAsFormDataAsync().Result;
return req.CreateResponse(HttpStatusCode.OK, "OK");
}
我收到以下错误:
Exception while executing function: System.Net.Http.Formatting: No MediaTypeFormatter is available to read an object of type 'FormDataCollection' from content with media type 'multipart/form-data'.
我正在尝试通过 SendGrid 解析入站电子邮件,如此处所述。 https://sendgrid.com/docs/Classroom/Basics/Inbound_Parse_Webhook/setting_up_the_inbound_parse_webhook.html
传入的请求看起来正确。
--xYzZY 内容处置:表单数据;名称=“附件”
0 --xYzZY 内容处置:表单数据;名称=“文本”
世界你好 --xYzZY 内容处置:表单数据;名称=“主题”
主题 --xYzZY 内容处置:表单数据;名称=“至”
最佳答案
由于似乎没有将 IFormCollection
转换为自定义模型/ View 模型类型的好方法,因此我为此编写了一个扩展方法。
遗憾的是,Azure Functions v2/v3 尚不支持开箱即用。
public static class FormCollectionExtensions
{
/// <summary>
/// Attempts to bind a form collection to a model of type <typeparamref name="T" />.
/// </summary>
/// <typeparam name="T">The model type. Must have a public parameterless constructor.</typeparam>
/// <param name="form">The form data to bind.</param>
/// <returns>A new instance of type <typeparamref name="T" /> containing the form data.</returns>
public static T BindToModel<T>(this IFormCollection form) where T : new()
{
var props = typeof(T).GetProperties();
var instance = Activator.CreateInstance<T>();
var formKeyMap = form.Keys.ToDictionary(k => k.ToUpper(), k => k);
foreach (var p in props)
{
if (p.CanWrite && formKeyMap.ContainsKey(p.Name.ToUpper()))
{
p.SetValue(instance, form[formKeyMap[p.Name.ToUpper()]].FirstOrDefault());
}
}
return instance;
}
}
这将尝试将 IFormCollection
绑定(bind)到您传入的任何模型类型。属性名称不区分大小写(即,您可以将 firstname=Bob
映射到 public字符串 FirstName { get; set; }
.
用法:
var myModel = (await httpReq.ReadFormAsync()).BindToModel<MyModel>();
关于c# - 如何使用 Azure Functions 解析表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45364128/