dotnet / dotnet/runtime

System.Drawing.Image Width and Height declare bool default values

Open
#126,265 4 comments 1 reaction 0 assignees View on GitHub
area-System.Drawing help wanted
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

### Description

The properties Width and Height of System.Drawing.Image have `[DefaultValue(false)]`, while their type is int (https://github.com/dotnet/dotnet/blob/b0f34d51fccc69fd334253924abd8d6853fad7aa/src/winforms/src/System.Drawing.Common/src/System/Drawing/Image.cs#L426).

I encountered this while trying to add openapi generation to an API. Image shouldn't be serialized in our API definition in the first place, but it's probably worth fixing so that it doesn't cause problems somewhere else.

### Reproduction Steps

I'm able to trigger the behavior in Microsoft.AspNetCore.OpenApi, I have tried creating the smallest web api that reproduces the behavior.

```
using Microsoft.AspNetCore.Mvc;
using System.Drawing;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddOpenApi();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

public class WeatherForecast
{
public Image? Image { get; set; } = null;
}

[ApiController]
[Route("test")]
public class WeatherForecastController : ControllerBase
{
public IEnumerable Get()
{
return [];
}
}
```

### Expected behavior

Width and Height declare a numerical default value: ``[DefaultValue(0)]`

### Actual behavior

When visiting http://localhost:5108/openapi/v1.json, OpenApi throws an invalid cast exception.

InvalidCastException: Unable to cast object of type 'System.Boolean' to type 'System.Int32'.

System.Text.Json.JsonSerializer.UnboxOnWrite(object value)
System.Text.Json.Serialization.Metadata.JsonTypeInfo.SerializeAsObject(Utf8JsonWriter writer, object rootValue)
System.Text.Json.JsonSerializer.WriteNodeAsObject(object value, JsonTypeInfo jsonTypeInfo)
Microsoft.AspNetCore.OpenApi.JsonNodeSchemaExtensions.ApplyDefaultValue(JsonNode schema, object defaultValue, JsonTypeInfo jsonTypeInfo)
Microsoft.AspNetCore.OpenApi.OpenApiSchemaService.<.ctor>b__0_2(JsonSchemaExporterContext context, JsonNode schema)
System.Text.Json.Schema.JsonSchema.g__CompleteSchema|100_0(JsonNode schema, ref <>c__DisplayClass100_0 )
[...]

### Regression?

I don't know.

### Known Workarounds

_No response_

### Configuration

.net 10, on Windows, x64. The platform probably does not matter.

### Other information

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.