Skip to content

API Proposal for gRPC JSON transcoding option to remove enum prefix #62891

@JamesNK

Description

@JamesNK

Background and Motivation

Protobuf uses C++ scoping rules for enum values which means they're global. To avoid collisions, the convention is to prefix the enum type name in values. e.g.

enum Status {
    STATUS_UNSPECIFIED = 0;
    STATUS_OK = 1;
    STATUS_FAILURE = 2;
}

This creates a bad experience so many Protobuf tools remove the prefix when generating code.

The proposed feature is a setting to remove the prefix when reading and writing enum names from JSON:

{
    "Status": "OK"
}

Addresses #58850

Proposed API

namespace Microsoft.AspNetCore.Grpc.JsonTranscoding;

public sealed class GrpcJsonSettings
{
+    /// <summary>
+    /// Gets or sets a value indicating whether the enum type name prefix should be removed when reading and writing enum values.
+    /// The default value is <see langword="false"/>.
+    /// </summary>
+    /// <remarks>
+    /// <para>
+    /// In Protocol Buffers, enum value names are globally scoped, so they are often prefixed with the enum type name
+    /// to avoid name collisions. For example, the <c>Status</c> enum might define values like <c>STATUS_UNKNOWN</c>
+    /// and <c>STATUS_OK</c>.
+    /// </para>
+    /// <code>
+    /// enum Status {
+    ///   STATUS_UNKNOWN = 0;
+    ///   STATUS_OK = 1;
+    /// }
+    /// </code>
+    /// <para>
+    /// <c>STATUS</c> prefix is removed from enum values when <see cref="RemoveEnumPrefix"/> is set to <see langword="true"/>.
+    /// The enum values above will be read and written as <c>UNKNOWN</c> and <c>OK</c> instead of <c>STATUS_UNKNOWN</c>
+    /// and <c>STATUS_OK</c>.
+    /// </para>
+    /// </remarks>
+    public bool RemoveEnumPrefix { get; set; }
}

Usage Examples

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddGrpc()
builder.Services.AddJsonTranscoding(o =>
{
    o.JsonSettings.RemoveEnumPrefix = true;
});

Alternative Designs

Risks

Technically the entire enum value must be matched according to the Protobuf JSON spec - protobuf.dev/programming-guides/json - but we'll call this out in docs so people can make an informed decision.

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-ready-for-reviewAPI is ready for formal API review - https://github.com/dotnet/apireviewsarea-grpcIncludes: GRPC wire-up, templates

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions