Skip to content

DataContent rejects RFC 2397 data URIs that give only a charset (data:;charset=utf-8,...) #7960

Open

Description

@dfedoryshchev

Description

RFC 2397 allows the text/plain part of the media type to be omitted while the charset is still given:

As a shorthand, "text/plain" can be omitted but the charset parameter supplied.

So data:;charset=utf-8,hello is a valid data URI.

DataContent throws on it. #7247 fixed the case where the whole media type is omitted (data:;base64,...), but when the metadata holds only parameters (with or without ;base64), DataUriParser.Parse hands ;charset=utf-8 to MediaTypeHeaderValue.TryParse, which fails:

ReadOnlySpan<char> span = metadata.Span.Trim();
string? mediaType = null;
if (span.IsEmpty)
{
mediaType = DefaultMediaType;
}
else if (!IsValidMediaType(span, ref mediaType))
{
throw new UriFormatException("Invalid data URI format: the media type is not a valid.");
}

Passing mediaType explicitly does not help, because the URI is parsed before the supplied media type is looked at:

_dataUri = DataUriParser.Parse(uri.AsMemory());
// Validate and store the media type.
mediaType ??= _dataUri.MediaType;

Reproduction Steps

using Microsoft.Extensions.AI;

var a = new DataContent("data:;charset=utf-8,hello");
var b = new DataContent("data:;charset=utf-8;base64,aGVsbG8=");
var c = new DataContent("data:;charset=utf-8,hello", "text/plain");

Expected behavior

All three parse to the bytes of hello. The first two get media type text/plain;charset=utf-8, the same as data:text/plain;charset=utf-8,hello; the third keeps the supplied text/plain.

Actual behavior

Each one throws:

System.UriFormatException: Invalid data URI format: the media type is not a valid.

Regression?

No, this shape never parsed as far as I can tell. #7247 covered only the empty media type.

Known Workarounds

Insert text/plain after data: before constructing the DataContent.

Configuration

main at 8cf4ff6658e9b36eca01ac6045ea9835f3b3b751, .NET 10.0.103 SDK, Windows 11 x64. Not configuration specific; the parsing is plain string handling.

Other information

Related: #7246 / #7247. Happy to send a PR with tests if this is wanted.

Activity

  1. added
    area-ai
    on Nov 18, 2026
  2. caigen commented on Nov 22, 2026

    @caigen

    Thanks @dfedoryshchev.
    While I was developing and improving my AI flow, my agent team auto picked this and generated one PR.
    Hope it can be reviewed and merged if possible. : )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-aiuntriaged

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions