How do you get a reference to HTTPResponse Object in Azure Functions?

Viewed 2270

I have an Azure v2 (and v3 preview) function (HTTP Trigger) that has a signature like this:

public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", 
        Route = null)] HttpRequest req,
        ILogger log)

I've checked the documentation and try as I might, I'm not able to find any reference to how I might get a reference to the HTTPResponse object as I would in ASP.NET, for instance.

I'm trying to set both a custom header as well as a custom cookie. The HTTPRequest object doesn't appear to have any access to anything response related.

2 Answers

use the following examples:

req.HttpContext.Response.Headers.Add("abcd", "12345");
req.HttpContext.Response.Cookies.Append("abcd", "12345");

If you want to set custom header you could refer to my below code:

public static class Function1
{
    [FunctionName("Function1")]
    public static HttpResponseMessage Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        string testheader = req.Headers.GetValues("testheader").FirstOrDefault();
        string executionTime = DateTime.UtcNow.ToString();

        var httpresponse = req.CreateResponse(HttpStatusCode.OK, new
        {
            Testheader = testheader,
            ExecutionTime = executionTime
        }, "application/json");
        httpresponse.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
        httpresponse.Headers.Add("Warning", "custom header");
        return httpresponse;
     
    }
}

This code add a custom header warning with 299 - "Deprecated API" value and change the content-type header.

enter image description here

Hope this could help you, if you still have other problem please feel free to let me know.

Related