c# - 如何使用 Azure Functions 解析表单数据

标签 c# function azure sendgrid

我正在尝试在 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/

相关文章:

javascript - 如何在 jQuery 中使用这个函数

javascript - 保留 Azure 移动服务的自定义 API 调用的用户身份验证

azure - 如何将 customDimensions 中的更多条目添加到 Azure Function 中的 Application Insights Telemetry

c# - TweetSharp 2.0 搜索和地理编码

c# - 在 asp.net identity 2.2.1 中使用密码哈希创建测试用户

c# - Asp.Net MVC Razor BootStrap 输入表单

c# - 模拟 Azure 表存储的 CloudStorageAccount 和 CloudTable

c# - 线程同步作业

arrays - 如何将一组未知数量的参数传递给 MATLAB 中的函数?

ios - 从 Swift 中的另一个 ViewController 访问 rightBarButton 函数