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);
}
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);
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With