我正在尝试在 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");
}
我收到以下错误:
执行函数时出现异常:System.Net.Http.Formatting:没有 MediaTypeFormatter 可用于从媒体类型为“multipart/form-data”的内容中读取类型为“FormDataCollection”的对象。
我正在尝试通过 SendGrid 解析入站电子邮件,如此处所述。https://sendgrid.com/docs/Classroom/Basics/Inbound_Parse_Webhook/setting_up_the_inbound_parse_webhook.html https://sendgrid.com/docs/Classroom/Basics/Inbound_Parse_Webhook/setting_up_the_inbound_parse_webhook.html
传入的请求看起来正确。
--xYzZY
内容处置:表单数据;名称=“附件”
0
--xYzZY
内容处置:表单数据;名称=“文本”
你好世界
--xYzZY
内容处置:表单数据;名称=“主题”
主题
--xYzZY
内容处置:表单数据;名称=“至”
由于似乎没有一个好的方法来转换IFormCollection
对于自定义模型/视图模型类型,我为此编写了一个扩展方法。
遗憾的是,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
到您传入的任何模型类型。属性名称不区分大小写(即您可以映射firstname=Bob
to public string FirstName { get; set; }
.
Usage:
var myModel = (await httpReq.ReadFormAsync()).BindToModel<MyModel>();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)