Model binding for function parameters for HTTP req

2019-07-22 04:48发布

问题:

Below is Azure Functions via C# with visual studio. The problem is that req.Form is used to create RequestDto object like below:

 public class Function1
{   
    [FunctionName("Token")]
    public async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]
    HttpRequest req)
    {

        var reqDto = new RequestDto
        {
            UserName = req.Form["username"],
            Password = req.Form["password"],
            ClientId = req.Form["client_id"],
            ClientSecret = req.Form["client_secret"]                
        };
       ...

      }
    }

Is it possible to use model binding that populates RequestDto automatically with ASP.NET CORE 2.x like below?

[Route("api/[controller]")]
[ApiController]
public class ConnectController : Controller
{
    [HttpPost("token")]
    [Consumes("application/x-www-form-urlencoded")]
    public async Task<IActionResult> Token([FromForm]RequestDto request)
    {
         ...
    }
 }

  public class RequestDto
  {
    [FromForm(Name="client_id")]
    public string ClientId { get; set; }

    [FromForm(Name = "client_secret")]
    public string ClientSecret { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
}

回答1:

I think what you are looking for is a custom binding or as called by Microsoft: Azure Functions/WebJobs binding extension. How to do this is explained here: https://github.com/Azure/WebJobsExtensionSamples