代码之家  ›  专栏  ›  技术社区  ›  tokyo0709

Azure函数V2将HttpRequest反序列化为对象

  •  1
  • tokyo0709  · 技术社区  · 6 年前

    我很惊讶我找不到这个问题的答案,但是我有一个Azure函数(HTTP触发器),我只是想将内容反序列化为一个对象。以前在V1上我能做到,

    功能V1

    [FunctionName("RequestFunction")]
    public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, TraceWriter log)
    {
        // Successful deserialization of the content
        var accountEvent = await req.Content.ReadAsAsync<AccountEventDTO>();
    
        // Rest of the function...
    }
    

    但现在V2看起来更像这样,

    函数V2

    [FunctionName("RequestFunction")]
    public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequest req, ILogger log)
    {
        // Content doesn't exist on HttpRequest anymore so this line doesn't compile
        var accountEvent = await req.Content.ReadAsAsync<AccountEventDTO>();
    
        // Rest of the function...
    }
    

    1 回复  |  直到 6 年前
        1
  •  17
  •   maccettura    5 年前

    API有点变化。如你所见 Content Microsoft.Azure.WebJobs.Extensions.Http

    string json = await req.ReadAsStringAsync();
    

    您可以查看此扩展方法的源代码 here

    然后使用Json.NET进行反序列化(Json.NET也已经是一个依赖项)

    var someModel = JsonConvert.DeserializeObject<SomeModel>(json);
    
        2
  •  7
  •   user3746240    5 年前

    例子:

    public static partial class SayHelloFunction
    {
        [FunctionName("SayHello")]
        public static async Task<ActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)]Person person, ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
    
            return person.Name != null ?
                    (ActionResult)new OkObjectResult($"Hello, {person.Name}")
                : new BadRequestObjectResult("Please pass an instance of Person.");
        }
    }
    

    public class Person
    {
        public Person()
        {
    
        }
        public Person(string name)
        {
            Name = name;
        }
    
        public string Name { get; set; }
    }
    

    HTTP请求:[POST] http://localhost:7071/api/SayHello 正文:{ 名字:“Foo”}

        3
  •  2
  •   René Marc Gravell    6 年前

    string json = await req.ReadAsStringAsync();
    dynamic data = JObject.Parse(json);