org.sonar.plugins.csharp.S6419.html Maven / Gradle / Ivy
Why is this an issue?
An Azure Function should be stateless as there’s no control over where and when function instances are provisioned and de-provisioned. Managing and
storing data/state between requests can lead to inconsistencies. If, for any reason, you need to have a stateful function, consider using the Durable
Functions extension of Azure Functions.
Noncompliant code example
public static class HttpExample
{
private static readonly int port = 2000;
private static int numOfRequests = 1;
[FunctionName("HttpExample")]
public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest request, ILogger log)
{
numOfRequests += 1; // Noncompliant
log.LogInformation($"Number of POST requests is {numOfRequests}.");
string responseMessage = $"HttpRequest was made on port {port}."; // Compliant, state is only read.
return new OkObjectResult(responseMessage);
}
}
Compliant solution
public static class HttpExample
{
private static readonly int port = 2000;
[FunctionName("HttpExample")]
public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest request, ILogger log)
{
// A compliant solution would be to manage the `numOfRequests` with an entity function or would use storage (e.g., Azure Blob storage, Azure Queue Storage)
// to share the state between functions.
string responseMessage = $"HttpRequest was made on port {port}.";
return new OkObjectResult(responseMessage);
}
}
Resources
© 2015 - 2024 Weber Informatics LLC | Privacy Policy