简体   繁体   English

Azure Functions V2将HttpRequest反序列化为对象

[英]Azure Functions V2 Deserialize HttpRequest as object

I'm surprised I can't find the answer to this but I've got an Azure function (HTTP Trigger) I simply want to deserialize the content as an object. 我很惊讶我找不到答案,但我有一个Azure功能(HTTP触发器)我只是想将内容反序列化为一个对象。 Previously with V1 I was able to do this, 以前用V1我能做到这一点,

Functions 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...
}

But now with V2 it looks more like this, 但现在使用V2看起来更像是这样,

Functions 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...
}

I can get the body to access the stream from the HttpRequest object but am unsure how I would cast that to the expected object. 我可以让主体从HttpRequest对象访问流,但我不确定如何将其转换为预期的对象。 Any ideas? 有任何想法吗?

The API has changed a bit. API发生了一些变化。 As you have seen Content does not exist anymore. 如您所见, Content不再存在。 However you can still get the same functionality by using the extension method that is included in the Microsoft.Azure.WebJobs.Extensions.Http namespace (which should be included already as a dependency): 但是,您仍然可以使用Microsoft.Azure.WebJobs.Extensions.Http命名空间中包含的扩展方法(它应该作为依赖项包含)来获得相同的功能:

string json = await req.ReadAsStringAsync();

You can view the source of this extension method here 您可以在此处查看此扩展方法的来源

Then you would use Json.NET to deserialize (Json.NET is already a dependency too) 然后你将使用Json.NET反序列化(Json.NET也已经是一个依赖)

var someModel = JsonConvert.DeserializeObject<SomeModel >(json);

If you don't know the type of your Object, you can do: 如果您不知道对象的类型,可以执行以下操作:

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

You can bind to a custom object instead of HttpRequest. 您可以绑定到自定义对象而不是HttpRequest。 This object is created from the body of the request and parsed as JSON. 此对象是从请求主体创建的,并解析为JSON。 Similarly, a type can be passed to the HTTP response output binding and returned as the response body, along with a 200 status code. 类似地,类型可以传递给HTTP响应输出绑定,并作为响应主体返回,同时返回200状态代码。 Example: 例:

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.");
    }
}

The model to bind to.. 要绑定的模型..

public class Person
{
    public Person()
    {

    }
    public Person(string name)
    {
        Name = name;
    }

    public string Name { get; set; }
}

The HTTP request: [POST] http://localhost:7071/api/SayHello Body: { name: "Foo" } HTTP请求:[POST] http:// localhost:7071 / api / SayHello正文 :{name:“Foo”}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM