AskMe
AskMe

Reputation: 2561

Azure function to return a specific string

I'm new to Azure function. And I have this simple .net core code as below:

 public static class HttpExample
{
    [FunctionName("HttpExample")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        string name = req.Query["name"];

        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        dynamic data = JsonConvert.DeserializeObject(requestBody);
        name = name ?? data?.name;

        return name != null
            ? (ActionResult)new OkObjectResult($"Hello, {name}")
            : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
    }
}

This code is working fine and returns Hello, Function. However, if I'm changing it to "world" like this :

   string name = req.Query["World"]; //may be I would like to try multiple strings with space? Just to have fun learning.

It returns me:

  Please pass a name on the query string or in the request body.

How can I return any specific string using this function?

Thanks.

Upvotes: 1

Views: 666

Answers (1)

akg179
akg179

Reputation: 1559

This is a HttpTrigger that you are trying to execute. The line string name = req.Query["name"]; is going to find the query-string parameter name in your request and will take the value from it.

How can I return any specific string using this function?

Whatever you assign to name query-string parameter, is the string that you will get in response.

For example, if you use this url in browser-

http://localhost:7071/api/HttpExample?name=Function

you will get Hello, Function in response because query["name"] will have value as 'Function'.

In order to return Hello, World you will have to provide a url something like this- http://localhost:7071/api/HttpExample?name=World

Upvotes: 3

Related Questions