Skip to content

ASP0019 should not fire if code guards with ContainsKey() #46907

@martincostello

Description

@martincostello

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

The new ASP0019 code analysis warning fires when the IHeaderDictionary.Append() method is used, even if the code uses the ContainsKey() method to check if the header is not already present before it is called.

if (!context.Response.Headers.ContainsKey("X-Frame-Options"))
{
    context.Response.Headers.Add("X-Frame-Options", "DENY");
}
ASP0019: Use IHeaderDictionary.Append or the indexer to append or set headers. IDictionary.Add will throw an ArgumentException when attempting to add a duplicate key.

Expected Behavior

No warning as the code has an appropriate guard clause.

Steps To Reproduce

Add a middleware with the following code to an ASP.NET Core 8 application:

public Task Invoke(RequestDelegate next, HttpContext context)
{
    context.Response.OnStarting(() =>
    {
        if (!context.Response.Headers.ContainsKey("X-Frame-Options"))
        {
            context.Response.Headers.Add("X-Frame-Options", "DENY");
        }

        return Task.CompletedTask;
    });

    return next(context);
}

Exceptions (if any)

N/A

.NET Version

8.0.100-preview.1.23115.2

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-networkingIncludes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions