Home > Back-end >  Azure function v4 dotnet-isolated - How do I read data in www-form-urlencoded?
Azure function v4 dotnet-isolated - How do I read data in www-form-urlencoded?

Time:06-22

I've created a bot that receives a slash command from slack users. I'm trying to access the payload of a slack message which has a content type of www-form-urlencoded.

I've tried parsing as a query:

[Function("SetSubject")]
public async Task<HttpResponseData> SetSubjectPost(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestData req, FunctionContext executionContext)
{
    var parsedFormBody = HttpUtility.ParseQueryString(req.Url.Query);
    var text = parsedFormBody["text"];
    var userId = parsedFormBody["user_id"];
}

I've tried getting it from the FunctionContext:

[Function("SetSubject")]
public async Task<HttpResponseData> SetSubjectPost(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestData req, FunctionContext executionContext)
{
    var text = executionContext.BindingContext.BindingData["text"]?.ToString();
    var userId = executionContext.BindingContext.BindingData["user_id"]?.ToString();
}

Also tried parsing the body as a MultipartFormData:

[Function("SetSubject")]
public async Task<HttpResponseData> SetSubjectPost(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestData req, FunctionContext executionContext)
{
    var parsedFormBody = await MultipartFormDataParser.ParseAsync(req.Body);
    var text = parsedFormBody.GetParameterValue("text");
    var userId = parsedFormBody.GetParameterValue("user_id");
}

Is there any way to get the data from www-form-urlencoded?

CodePudding user response:

You need to read the body as string then parse it as a querystring:

[Function("SetSubject")]
public async Task<HttpResponseData> SetSubjectPost(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestData req, FunctionContext executionContext)
{
    // Read body
    var stringBody = await new StreamReader(req.Body).ReadToEndAsync();

    // Parse as query string
    var keyValues = HttpUtility.ParseQueryString(stringBody);
    var text = keyValues["text"];
    var userId = keyValues["user_id"];

    ...
}

  • Related