Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Content Type Header in Azure Function

How can I return HTTP Content-Type "application/json" header? Can not find a sample in net...

[FunctionName("Function1")]
public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log)
{
    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

    Dictionary<string, string> dd = Parser(requestBody);
    string json = JsonConvert.SerializeObject(dd);

    if (json == null)
    {
        return new BadRequestObjectResult("Please pass request body");
    }

    return (ActionResult)new OkObjectResult(json);
}
like image 763
Cherven Avatar asked Sep 17 '25 07:09

Cherven


2 Answers

You could do this by accessing the Response object via the request's HttpContext:

[FunctionName("Function1")]
public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log)
{
    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

    Dictionary<string, string> dd = Parser(requestBody);
    string json = JsonConvert.SerializeObject(dd);

    if (json == null)
    {
        return new BadRequestObjectResult("Please pass request body");
    }

    //add this line...
    req.HttpContext.Response.Headers.Add("Content-Type", "application/json");

    return (ActionResult)new OkObjectResult(json);
}
like image 198
Rena Avatar answered Sep 19 '25 22:09

Rena


1 - By specifying it in your request "Accept : application/json". Azure functions will natively return the type requested in the Accept header. Your code should already be correctly honouring that request.

2 - By returning a JsonResult The following code will ignore the Accept header and return "application/json" in every case - your serialization is redundant.

[FunctionName("Function1")]

public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log)
{
    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

    Dictionary<string, string> dd = Parser(requestBody);

    if (dd == null) return new BadRequestObjectResult("Please pass request body");

    return (ActionResult) new JsonResult(dd);
    //return (ActionResult) new OkObjectResult(dd);
}
like image 45
David Lapeš Avatar answered Sep 19 '25 23:09

David Lapeš