skip to content

API Contracts & Protocols

Describing and shaping web APIs in ASP.NET Core: OpenAPI documents, Asp.Versioning, gRPC services, OData query endpoints and DTO mapping. Interviewers probe how an API's contract is kept stable.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

27

In ASP.NET Core 10, how do you host a gRPC service defined in a .proto file, and what do Grpc.Tools, AddGrpc and MapGrpcService each do?

level: juniorimportance: must knowfreq 50%

answer

  1. Grpc.AspNetCore metapackage
  2. <Protobuf GrpcServices="Server">
  3. override the generated ...Base class
  4. AddGrpc, then MapGrpcService<T>()
  5. Kestrel EndpointDefaults Protocols Http2

basics

~10 s

Reference Grpc.AspNetCore, add the .proto as a <Protobuf> item so Grpc.Tools generates a base class at build time, override its methods, then call builder.Services.AddGrpc() and app.MapGrpcService<T>(). Calls must arrive over HTTP/2.

solid answer

~40 s

The `Grpc.AspNetCore` package brings the server, `Google.Protobuf` and `Grpc.Tools`. A `<Protobuf Include="Protos\pricequote.proto" GrpcServices="Server" />` item makes Grpc.Tools run `protoc` on every build and write C# into `obj`: message classes plus a `PriceQuote.PriceQuoteBase` class with one virtual method per rpc. Your `PriceQuoteService` derives from it and overrides `GetQuote(QuoteRequest request, ServerCallContext context)`. `builder.Services.AddGrpc()` registers the gRPC server services and returns an `IGrpcServerBuilder` for options; `app.MapGrpcService<PriceQuoteService>()` maps each rpc as a POST endpoint such as `/pricing.PriceQuote/GetQuote`. The service is created per call from the request's services unless you register it yourself. gRPC needs HTTP/2, so `dotnet new grpc` sets Kestrel's `EndpointDefaults:Protocols` to `Http2`; an HTTP/1.1 request that does reach a gRPC endpoint gets 426.

code

xml · 7 lines
xml
<ItemGroup>
  <Protobuf Include="Protos\pricequote.proto" GrpcServices="Server" />
</ItemGroup>

<ItemGroup>
  <PackageReference Include="Grpc.AspNetCore" Version="2.84.0" />
</ItemGroup>

go deeper

for a junior

Recall the chain: .proto item, generated base class, override, AddGrpc, MapGrpcService, and that the template restricts Kestrel to HTTP/2.

for a middle

Explain the Protobuf item metadata, where generated code lives, how the service instance is created per call, and the 426 for HTTP/1.1.

for a senior

Configure message size limits and detailed errors per environment, and decide how the shared .proto is consumed by server and client projects.

for a principal

Decide where gRPC fits beside JSON endpoints across services, and who owns contract changes once several teams compile against one .proto.

## The moving parts An ASP.NET Core gRPC service is ordinary ASP.NET Core hosting plus generated code. The pieces: | Piece | Role | |---|---| | `.proto` file | the contract: messages and a `service` with its rpc methods | | `Grpc.Tools` | MSBuild integration that runs `protoc` and the C# gRPC plugin during build | | `Grpc.AspNetCore` | metapackage: the server (`Grpc.AspNetCore.Server`), `Google.Protobuf`, `Grpc.Tools` and the client factory | | `AddGrpc()` | registers the gRPC server services in DI | | `MapGrpcService<T>()` | maps the service's methods into endpoint routing | ## Code generation from the .proto The project file lists the contract as a `Protobuf` item. Grpc.Tools reads its metadata: - `GrpcServices` chooses what is generated: `Both` (the default), `Server`, `Client` or `None` (messages only). - `Access` defaults to `Public`; `Internal` makes generated types internal. - `OutputDir` defaults to the intermediate output path, so generated files live under `obj`, not in source control. For a contract with `option csharp_namespace = "Pricing";` and `service PriceQuote`, the build produces message classes such as `QuoteRequest` and a static `PriceQuote` class holding the abstract base class `PriceQuote.PriceQuoteBase`. Every rpc becomes a virtual method; one you do not override answers with the `Unimplemented` status. ## Registration and mapping 1. `builder.Services.AddGrpc(options => ...)` registers the server. The options (`GrpcServiceOptions`) include `MaxReceiveMessageSize` (4 MB by default), `MaxSendMessageSize` (unlimited by default), `EnableDetailedErrors` and `Interceptors`. 2. `app.MapGrpcService<PriceQuoteService>()` adds one endpoint per rpc. Each is a POST endpoint whose path is the method's full name, `/pricing.PriceQuote/GetQuote`, and it returns a `GrpcServiceEndpointConventionBuilder`, so `RequireAuthorization()` or `EnableGrpcWeb()` can be chained. 3. Per call, the service class is resolved from the request's service provider if you registered it; otherwise it is created with its constructor dependencies and disposed after the call. Constructor injection of scoped services such as a `DbContext` is therefore safe. ## HTTP/2 is required The server checks the request protocol before running a handler. Over HTTP/2 (or HTTP/3) the call proceeds; over HTTP/1.1 it answers **426 Upgrade Required** with an `Upgrade: HTTP/2` header and the message "Request protocol 'HTTP/1.1' is not supported." The `grpc` template therefore writes this into `appsettings.json`: - `"Kestrel": { "EndpointDefaults": { "Protocols": "Http2" } }` Serving HTTP/1.1 and HTTP/2 on the same port requires TLS, because the protocol is negotiated during the TLS handshake. Kestrel endpoint configuration itself is a hosting topic. ## Errors from a handler - Throw `new RpcException(new Status(StatusCode.NotFound, "No quote for XYZ"))` to return a specific status and message. - Any other exception becomes `StatusCode.Unknown` with "Exception was thrown by handler."; the exception text is added only when `EnableDetailedErrors` is true, which belongs in Development only. ## What the template creates `dotnet new grpc` writes `Protos/greet.proto` with `GrpcServices="Server"`, a `GreeterService` deriving from `Greeter.GreeterBase`, `AddGrpc()`, `MapGrpcService<GreeterService>()` and a `GET /` that tells browsers to use a gRPC client. The ASP.NET Core 10.0.12 template pins `Grpc.AspNetCore` 2.64.0, older than the current 2.84 release, so a new project is worth updating before work starts. ## Sharing one contract between server and clients The price-quote contract is consumed by the service and by every back end that calls it. Common layouts: - Keep the `.proto` files in one folder or repository and reference them from each project with `<Protobuf Include="..\contracts\pricequote.proto" GrpcServices="Client" Link="Protos\pricequote.proto" />`, so each side generates only what it needs. - The `dotnet-grpc` global tool writes these items: `dotnet-grpc add-file ..\contracts\pricequote.proto --services Server` adds the reference with the chosen services value, and `add-url` downloads a contract from a URL. - Avoid one shared class library that generates `Both` for everyone unless the server and clients really ship together; it couples their release cadence to the library's. Whatever the layout, generated code is rebuilt from the `.proto` on every build, so the contract file, not the generated C#, is what goes through review.

  • A caller sends a 6 MB request message to the price-quote service. What happens and how do you change it?
    `MaxReceiveMessageSize` defaults to 4 MB, so the server fails the call with `ResourceExhausted` and "Received message exceeds the maximum configured message size." Raise it globally in `AddGrpc(o => o.MaxReceiveMessageSize = ...)` or for one service with `AddServiceOptions<PriceQuoteService>(...)`; a `null` value removes the limit. The .NET client has the same 4 MB receive default.
  • Why might you register PriceQuoteService in DI yourself?
    Only when you want a lifetime other than per call, for example a singleton holding expensive state. If the type is registered, the activator takes that instance and does not dispose it; otherwise it creates one per call with constructor injection and disposes it afterwards.

  • The generated C# files must be committed, because Grpc.Tools only runs once.
  • A gRPC service class is a singleton unless it is registered with AddScoped.
  • MapGrpcService works over HTTP/1.1 as well, so the template's Http2 setting is optional.
  • An unhandled exception in a handler is returned to the caller with its full message by default.
  • GrpcServices="Both" is required on the server, or MapGrpcService cannot find the service.

Assumes ASP.NET Core 10 with Grpc.AspNetCore 2.84; the 10.0.12 grpc template still pins Grpc.AspNetCore 2.64.0, and the template's Http2-only Kestrel default is read from that release.

open as a page

In an ASP.NET Core 10 Minimal API, what goes wrong when GET /employees/{id} returns the EF Core Employee entity instead of an EmployeeDto record?

level: juniorimportance: must knowfreq 72%

basics

~20 s

Returning the entity hands System.Text.Json every public property, so Salary and any column added later leak, loaded navigations can throw an object-cycle JsonException, and the JSON contract changes whenever the table does. A response record lists exactly what is public.

open as a page

In ASP.NET Core 10, what do AddOpenApi and MapOpenApi do, and at which URL is the default OpenAPI document served?

level: juniorimportance: must knowfreq 70%

basics

~20 s

AddOpenApi registers ASP.NET Core's built-in OpenAPI generator for a document named v1, and MapOpenApi adds a GET endpoint that builds and serves it at /openapi/v1.json. The webapi template maps it only in Development and ships no UI.

open as a page

In ASP.NET Core, how do you add API versioning with the Asp.Versioning 10 packages, and what do its defaults do with an unversioned request?

level: juniorimportance: must knowfreq 55%

basics

~20 s

Asp.Versioning.Http (Minimal APIs) or Asp.Versioning.Mvc (controllers, via .AddMvc()) plus services.AddApiVersioning(). By default versions come from the api-version query parameter or a URL segment, nothing is assumed, so a request to a versioned endpoint without a version gets 400.

open as a page

In ASP.NET Core with EF Core, why does a PUT handler that binds the body to the Employee entity and calls db.Update let a caller rewrite Salary?

level: middleimportance: must knowfreq 55%

basics

~20 s

The JSON body is deserialized straight onto Employee, so any property the caller sends, Salary included, is set, and any it omits arrives as a default. db.Update then marks every column modified, so SaveChanges writes both into the row.

open as a page

In ASP.NET Core OData, what does [EnableQuery] do with an IQueryable<SalesOrder> result, and why can $filter still fail until ODataOptions enables it?

level: middleimportance: must knowfreq 32%

basics

~20 s

[EnableQuery] is an MVC action filter that validates the request's OData options, then composes them onto the IQueryable the action returns. Each option must also be enabled on ODataOptions, where Filter, Select and the others start off.

open as a page

In ASP.NET Core 10, how does endpoint metadata such as WithName, WithSummary and Produces reach the generated OpenAPI document?

level: middleimportance: must knowfreq 55%

basics

~20 s

The generator never reads handler bodies: ApiExplorer turns each endpoint's metadata into an ApiDescription, and the OpenAPI service maps it, WithName to operationId, WithSummary and WithDescription to summary and description, Produces and [ProducesResponseType] to responses.

open as a page

With Asp.Versioning 10 Minimal APIs, how do you run v1 and v2 of a loyalty-points API side by side with NewVersionedApi or NewApiVersionSet?

level: middleimportance: must knowfreq 50%

basics

~20 s

Call app.NewVersionedApi("Loyalty"), map one group per version with HasApiVersion(1.0) and HasApiVersion(2.0), or build an ApiVersionSet with NewApiVersionSet() and attach it with WithApiVersionSet plus MapToApiVersion. Each request is routed to the handler for its requested version.

open as a page

In ASP.NET Core gRPC, how do you write and register a server interceptor, and how does it differ from ASP.NET Core middleware?

level: middleimportance: should knowfreq 33%

basics

~10 s

Derive from Interceptor, override UnaryServerHandler (and the streaming handlers you need), and register it with AddGrpc(o => o.Interceptors.Add<T>()) or AddServiceOptions<TService>. Unlike middleware it runs only for gRPC calls and sees typed messages and ServerCallContext.

open as a page

In an ASP.NET Core gRPC service, how do you implement a server-streaming method, and what does ServerCallContext give the handler?

level: middleimportance: should knowfreq 38%

basics

~10 s

Override the generated method, which receives the request, an IServerStreamWriter<T> and a ServerCallContext; loop calling WriteAsync until context.CancellationToken fires. ServerCallContext carries the deadline, cancellation token, headers, trailers, status and, through GetHttpContext(), the HttpContext.

open as a page

In an ASP.NET Core 10 codebase, how do you test DTO mappings so a new Employee column is neither silently dropped nor leaked into a response?

level: middleimportance: should knowfreq 33%

basics

~20 s

Match the safety net to the mapper: compile errors from positional records for hand-written code, AssertConfigurationIsValid in a unit test for AutoMapper, Mapperly's RMG012 and RMG020 raised to errors, plus one response-level test that the JSON contains no salary.

open as a page

With [EnableQuery] in ASP.NET Core OData, what changes when an action returns a materialized List<SalesOrder> instead of an EF Core IQueryable, and what risks remain?

level: middleimportance: should knowfreq 26%

basics

~20 s

A List means every row was already read and [EnableQuery] filters and pages it in memory; an IQueryable lets the options compose into one database query. Clients still shape that query, so limits and a trimmed EDM remain necessary.

open as a page

In a .NET 10 ASP.NET Core API, when would you keep Swashbuckle or NSwag instead of the built-in Microsoft.AspNetCore.OpenApi generator?

level: middleimportance: should knowfreq 50%

basics

~20 s

New .NET 10 APIs normally use Microsoft.AspNetCore.OpenApi. Keep Swashbuckle when an existing app relies on its filters, annotations, CLI or Swagger 2.0 output, and NSwag when you also want its C# or TypeScript client generation from the same toolchain.

open as a page

In ASP.NET Core 10, how would you use OpenAPI transformers to add a JWT bearer security scheme to a public flight-status API's document?

level: middleimportance: should knowfreq 45%

basics

~10 s

Register an IOpenApiDocumentTransformer with options.AddDocumentTransformer<T>() inside AddOpenApi. It adds an http bearer scheme to document.Components.SecuritySchemes; an operation transformer then adds a requirement referencing it to every endpoint that is not anonymous.

open as a page

When moving loyalty-points clients from v1 to v2 with Asp.Versioning 10, what do AssumeDefaultVersionWhenUnspecified, the version selector, ReportApiVersions and sunset policies each do?

level: middleimportance: should knowfreq 40%

basics

~10 s

AssumeDefaultVersionWhenUnspecified lets unversioned requests through by asking the ApiVersionSelector for a version, 1.0 with the default selector. ReportApiVersions adds api-supported-versions and api-deprecated-versions headers, and options.Policies.Sunset or Deprecate adds dated policy headers for a version.

open as a page

In an ASP.NET Core controller versioned with Asp.Versioning 10, what do [ApiVersion], [MapToApiVersion] and [ApiVersionNeutral] do, and how do two actions share one route?

level: middleimportance: should knowfreq 45%

basics

~20 s

[ApiVersion] on a controller declares the versions it implements, [MapToApiVersion] on an action narrows that action to one of them, and [ApiVersionNeutral] opts a controller or action out. Two actions on one route split versions this way; it needs AddApiVersioning().AddMvc().

open as a page

When an ASP.NET Core gRPC service calls another gRPC service, how do AddGrpcClient, deadlines and EnableCallContextPropagation keep the chain bounded?

level: seniorimportance: should knowfreq 30%

basics

~10 s

Register the downstream client with AddGrpcClient<T>(o => o.Address = ...), pass a deadline on each call, and add EnableCallContextPropagation() so calls made inside a gRPC handler inherit the incoming call's deadline and cancellation token.

open as a page

With EF Core 10 in an ASP.NET Core API, why can .Select(e => e.ToDto()) read every Employee column while .Select(e => new EmployeeDto(...)) reads only the projected ones?

level: seniorimportance: should knowfreq 42%

basics

~20 s

EF Core cannot see inside a compiled ToDto method, so it evaluates that final Select on the client: it loads the whole Employee row, Salary included, and tracks it. An inline new EmployeeDto(...) is an expression EF Core translates into a SELECT of just those columns.

open as a page

You expose SalesOrders through ASP.NET Core OData to an analytics tool; which [EnableQuery] and ODataOptions settings stop it from pulling the whole table or running runaway queries?

level: seniorimportance: should knowfreq 22%

basics

~20 s

Set PageSize so every response is a page with a next link, cap $top globally with SetMaxTop and per action with MaxTop, and narrow AllowedQueryOptions, AllowedFunctions, AllowedOrderByProperties, MaxExpansionDepth and MaxNodeCount to what the tool needs.

open as a page

When you upgrade an ASP.NET Core 9 API with custom OpenAPI transformers to .NET 10, what changes in the generated document and what breaks?

level: seniorimportance: should knowfreq 35%

basics

~20 s

ASP.NET Core 10 emits OpenAPI 3.1 by default and builds on Microsoft.OpenApi 2, so transformers using Nullable, OpenApiAny, string schema types or Reference objects must be rewritten, even if OpenApiVersion is set back to OpenApi3_0.

open as a page

In ASP.NET Core 10 with Asp.Versioning, how do you publish one OpenAPI document per API version for the built-in Microsoft.AspNetCore.OpenApi generator?

level: seniorimportance: should knowfreq 30%

basics

~10 s

Add Asp.Versioning.OpenApi, chain .AddApiExplorer(o => o.GroupNameFormat = "'v'VVV") and .AddOpenApi() on AddApiVersioning, then call app.MapOpenApi().WithDocumentPerVersion(). Each version gets its own document, such as /openapi/v1.json and /openapi/v2.json.

open as a page

With Asp.Versioning 10, how do you accept the version from a header or media type, and what happens when a request carries two conflicting versions?

level: seniorimportance: should knowfreq 35%

basics

~10 s

Set ApiVersioningOptions.ApiVersionReader to ApiVersionReader.Combine(...) with a HeaderApiVersionReader naming the header and, if wanted, a MediaTypeApiVersionReader for the v parameter. If the readers return two different version strings, the request gets 400 AmbiguousApiVersion.

open as a page

After AutoMapper became a commercial Lucky Penny product in 15.0, how would you choose a mapping approach for a large ASP.NET Core codebase that uses it everywhere?

level: principalimportance: should knowfreq 30%

basics

~20 s

Treat it as a licence decision plus a migration-cost decision: AutoMapper 15+ is RPL-1.5 or commercial, enforced only by log messages, while Mapperly is an Apache-2.0 source generator. Inventory how the codebase uses AutoMapper, then pay, migrate gradually, or hand-write.

open as a page

In ASP.NET Core 10 with Microsoft.AspNetCore.OData, how do AddOData, an EDM model and AddRouteComponents expose a SalesOrders entity set through an ODataController?

level: juniorimportance: nice to knowfreq 18%

basics

~10 s

Chain AddOData onto AddControllers, build an IEdmModel with ODataConventionModelBuilder and EntitySet<SalesOrder>("SalesOrders"), and register it under a prefix with AddRouteComponents. A SalesOrdersController deriving from ODataController then answers /odata/SalesOrders by convention.

open as a page

How do you let a browser call an ASP.NET Core gRPC price-quote service through gRPC-Web, and what must change in the app's configuration?

level: seniorimportance: nice to knowfreq 22%

basics

~10 s

Add Grpc.AspNetCore.Web, call app.UseGrpcWeb(), opt the service in with EnableGrpcWeb() because GrpcWebOptions.DefaultEnabled is false, allow HTTP/1.1 on the Kestrel endpoint, and for cross-origin pages add a CORS policy exposing the grpc-status headers.

open as a page

With ASP.NET Core 10 gRPC JSON transcoding, how do you expose the price-quote service as a JSON HTTP API, and what are its limits?

level: seniorimportance: nice to knowfreq 15%

basics

~10 s

Add Microsoft.AspNetCore.Grpc.JsonTranscoding, call AddGrpc().AddJsonTranscoding(), set IncludeHttpRuleProtos to import google/api/annotations.proto, and annotate each rpc with option (google.api.http). Only annotated unary and server-streaming methods become JSON endpoints.

open as a page

In ASP.NET Core 10, how does build-time OpenAPI document generation work, and what can go wrong when it runs your Program.cs?

level: seniorimportance: nice to knowfreq 22%

basics

~20 s

Adding Microsoft.Extensions.ApiDescription.Server makes every build run the app's entry point under a mock server, ask the registered generator for each document and write {ProjectName}.json to obj by default; startup code that needs real infrastructure must be guarded.

open as a page