Skip to content

fix(http-server-csharp): handle void success responses - #11905

Merged
sophia-ramsey merged 5 commits into
mainfrom
sramsey/csharp-void-success
Sep 14, 2026
Merged

sophia-ramsey merged 5 commits into
mainfrom
sramsey/csharp-void-success

Conversation

@sophia-ramsey

Copy link
Copy Markdown
Member

This pull request improves the handling of union return types that include void and @error responses in generated C# controllers. The main fix ensures that when an operation can return either void (success) or an error, the generated controller method will correctly treat the success case as a bodyless response (HTTP 204 No Content), aligning with C# and HTTP conventions. Tests are added to verify this behavior, and the response analysis logic is updated accordingly.

C# Controller Generation Fixes:

  • Ensured that operations returning void | @error are generated as bodyless success responses (HTTP 204 No Content) in C# controllers. (.chronus/changes/csharp-void-success-2026-09-08.md)
  • Updated getSuccessStatusCode to detect unions with void and error types, returning the correct status code and body handling. (response-analysis.ts)

Testing Improvements:

  • Added tests to verify that for void | @error unions, the controller does not assign a result variable and returns NoContent(), and for value unions, it preserves result handling and returns the value. (controller-action.test.tsx)

Internal Refactoring:

  • Updated the getSuccessStatusCode function signature and its usage to accept the program parameter, supporting improved error model detection. (controller-action.tsx, response-analysis.ts) [1] [2]

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@pkg-pr-new

pkg-pr-new Bot commented Sep 9, 2026

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/@typespec/http-server-csharp@11905

commit: 92662f0

@github-actions

github-actions Bot commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

All changed packages have been documented.

  • @typespec/http-server-csharp
Show changes

@typespec/http-server-csharp - fix ✏️

Handle void | @error responses as bodyless success responses in generated C# controllers.

@azure-sdk-automation

azure-sdk-automation Bot commented Sep 10, 2026

Copy link
Copy Markdown

You can try these changes here

🛝 Playground 🌐 Website 🛝 VSCode Extension

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

The change is a targeted emitter bug fix with an appropriate .chronus entry and added tests/snapshot updates that directly cover the new behavior.

Pull request overview

This PR fixes C# controller generation in @typespec/http-server-csharp so that operations whose success type is void but also include @error union variants are emitted as bodyless success responses (HTTP 204 No Content), rather than incorrectly generating Ok(result).

Changes:

  • Updated success-response analysis to skip @error union variants and prefer 204/no-body when the only success variant is void.
  • Wired the controller action generator to pass program into response analysis for proper @error detection.
  • Added/updated tests and snapshots to verify the generated controller code for void | @error and value-or-error unions.
File summaries
File Description
packages/http-server-csharp/test/snapshots/sample-service/generated/controllers/PetsController.cs Snapshot update reflecting NoContent() + 204 for a void success union case.
packages/http-server-csharp/src/components/controller-action/response-analysis.ts Adjusted getSuccessStatusCode to use isErrorModel(program, ...) and return 204/no-body for void success unions.
packages/http-server-csharp/src/components/controller-action/controller-action.tsx Updated callsite to pass $.program into getSuccessStatusCode.
packages/http-server-csharp/src/components/controller-action/controller-action.test.tsx Added coverage for `void
.chronus/changes/csharp-void-success-2026-09-08.md Added a fix changelog entry for the user-visible emitter behavior change.
Review details
  • Files reviewed: 4/5 changed files
  • Comments generated: 0
  • Review effort level: Lite

💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Copilot AI review requested due to automatic review settings September 10, 2026 21:07

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Scalar success variants in unions may incorrectly produce 204, and one test does not exercise the new union path.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details

Suppressed comments (1)

Previously missed (1) — in code that hasn't changed since the last review.

packages/http-server-csharp/src/components/controller-action/controller-action.test.tsx:147

  • This test instantiates ServiceOperation<string>, so the operation has no void success variant and getSuccessStatusCode uses the unchanged fallback path; the expectation therefore also passes with the pre-change implementation. Instantiate a value-plus-void union (for example ServiceOperation<string | void>) or add a separate case so the new union handling is actually exercised and the scalar regression is covered.
  • Files reviewed: 4/5 changed files
  • Comments generated: 1
  • Review effort level: Lite

Copilot AI review requested due to automatic review settings September 11, 2026 22:15

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Response analysis still has unresolved cases that can produce incorrect metadata or non-compiling generated controllers.

Get a fresh assessment by requesting another Copilot review.

Review details

Suppressed comments (5)

packages/http-server-csharp/src/components/controller-action/response-analysis.ts:43

  • This returns immediately for a bodyless success model even when another union variant is a value. For NoContentResponse | string (or the reverse order), hasBody becomes false while getSuccessReturnType produces Task<string>, so the generated action discards the value and always returns NoContent(); keep scanning and prefer a body/value success when one exists.
        for (const variant of type.variants.values()) {
          const result = analyzeVariant(variant.type);
          if (result !== undefined) return result;
        }

packages/http-server-csharp/src/components/controller-action/response-analysis.ts:49

  • getSuccessReturnType still treats a model named exactly Error as an error (return-type-helpers.ts:26-34), but this branch only calls isErrorModel. For void | Error without an @error decorator, the interface is generated as Task while hasBody is true, so the controller emits var result = await ... against a non-generic Task and fails to compile; apply the same name-convention check here.
        if (isErrorModel(program, type)) return undefined;

packages/http-server-csharp/src/components/controller-action/response-analysis.ts:67

  • When every variant is an error, neither hasValueSuccess nor hasVoidSuccess is set, so this falls through to the generic { statusCode: 200, hasBody: true } result below. getSuccessReturnType now returns undefined for the same union, causing a Task business method but controller code that assigns var result and calls Ok(result), which does not compile; handle the no-success case consistently and add an error-only-union regression test.
    if (hasValueSuccess) {
      return { statusCode: 200, hasBody: true };
    }
    if (hasVoidSuccess) {
      return { statusCode: 204, hasBody: false };

packages/http-server-csharp/src/components/controller-action/response-analysis.ts:51

  • This filters @error models for union analysis, but direct error return types still take the direct-model path above and are treated as body-bearing successes. Because getSuccessReturnType now returns no success type for a direct @error model, the generated interface is Task while the controller still emits a result assignment/Ok(result); apply the same no-success handling to direct error models and cover that input.
      if (type.kind === "Model") {
        // Skip models with @error decorator or error-range status codes
        if (isErrorModel(program, type)) return undefined;
        const result = analyzeResponseModel(type);
        if (result.statusCode !== undefined && result.statusCode >= 400) return undefined;

packages/http-server-csharp/src/utils/return-type-helpers.ts:29

  • This now returns undefined for a direct, body-bearing @error model, while getSuccessStatusCode still treats a direct model as bodyful (response-analysis.ts:18-20). The interface therefore emits Task, but the controller emits var result = await ..., which does not compile for an error-only operation. Keep direct-model response analysis consistent (or explicitly handle/reject error-only operations) and add a regression test.
    if (type.kind === "Model") {
      try {
        if (isErrorModel(program, type)) return undefined;
  • Files reviewed: 6/7 changed files
  • Comments generated: 1
  • Review effort level: Lite

@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Sep 14, 2026
Copilot AI review requested due to automatic review settings September 14, 2026 17:15

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Two critical correctness issues remain in union success-type and error analysis.

Get a fresh assessment by requesting another Copilot review.

Review details

Suppressed comments (2)

packages/http-server-csharp/src/components/controller-action/response-analysis.ts:51

  • getSuccessReturnType deliberately skips status-code-only models and will select a later value variant, but this branch returns a no-body analyzeResponseModel result immediately. For a union such as NoContentResponse | string (or the equivalent nested union), the interface is Task<string> while the controller emits await ...; return NoContent(), silently dropping the successful value; defer bodyless candidates until all variants are examined so body handling matches the selected success type.
        const result = analyzeResponseModel(type);
        if (result.statusCode !== undefined && result.statusCode >= 400) return undefined;

packages/http-server-csharp/src/utils/return-type-helpers.ts:29

  • This now skips @error models for a standalone return type, but getSuccessStatusCode still takes the direct-model path and reports hasBody: true. That leaves the business interface/mock with non-generic Task while ControllerAction emits var result = await ..., which cannot compile; classify direct error returns as bodyless in the response analysis too (and add a regression test).
        if (isErrorModel(program, type)) return undefined;
  • Files reviewed: 6/7 changed files
  • Comments generated: 2
  • Review effort level: Lite

Comment thread packages/http-server-csharp/src/components/controller-action/response-analysis.ts Outdated
Comment thread packages/http-server-csharp/src/utils/return-type-helpers.ts
Copilot AI review requested due to automatic review settings September 14, 2026 18:26

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved response-analysis and return-type inconsistencies need correction before approval.

Get a fresh assessment by requesting another Copilot review.

Review details

Suppressed comments (4)

packages/http-server-csharp/src/components/controller-action/response-analysis.ts:72

  • When a scalar success precedes a body model with an explicit status code, this returns the later model's status (for example 201) even though getSuccessReturnType selects the earlier scalar. The added string | CreatedPet case therefore declares ProducesResponseType(200, typeof(string)) but returns StatusCode(201, result); select one consistent success variant/status or derive the metadata from the selected status.
    const result = analyzeVariant(returnType);
    if (result !== undefined) {
      return result;
    }
    if (hasValueSuccess) {
      return { statusCode: 200, hasBody: true };

packages/http-server-csharp/src/utils/return-type-helpers.ts:29

  • The new direct-error branch in getSuccessReturnType is not covered: the controller test for a direct error has hasBody === false, so ControllerAction skips this helper, and the interface tests only cover error unions. Add a direct @error model case for the business-logic interface or mock generation to verify it remains non-generic Task rather than regressing to Task<ErrorResponse>.
    if (type.kind === "Model") {
      try {
        if (isErrorModel(program, type)) return undefined;

packages/http-server-csharp/src/utils/return-type-helpers.ts:40

  • getSuccessReturnType does not apply the same statusCode >= 400 filtering used by getSuccessStatusCode below. For NotFound | string where NotFound has @statusCode statusCode: 404, response analysis selects the string/200 success but this helper selects NotFound, so the generated interface return type and ProducesResponseType type disagree with the selected success response; apply the same error-range classification here.
    // Skip error models by checking the @error decorator or name convention
    if (type.kind === "Model") {
      try {
        if (isErrorModel(program, type)) return undefined;
      } catch {
        // isErrorModel may fail on certain types
      }
      if (type.name && type.name.toLowerCase() === "error") {
        return undefined;
      }
      // Skip response-only models (only @statusCode, no body props)
      if (isStatusCodeOnlyModel(type)) {
        return undefined;
      }
    }

packages/http-server-csharp/src/utils/return-type-helpers.ts:21

  • Recursing through every nested union and returning its first leaf narrows the generated business-logic contract. For example, void | PetType where PetType is a named string union now produces Task<string> instead of the PetType type supported by TypeExpression, and a nested string | int32 can no longer return the second variant; preserve unions with multiple success variants (and named union enums) for interface/mock generation, and only flatten them for response metadata.
      for (const variant of type.variants.values()) {
        const successType = findSuccessType(variant.type);
        if (successType !== undefined) return successType;
  • Files reviewed: 6/7 changed files
  • Comments generated: 1
  • Review effort level: Lite

@sophia-ramsey
sophia-ramsey added this pull request to the merge queue Sep 14, 2026
Merged via the queue into main with commit 784e087 Sep 14, 2026
35 checks passed
@sophia-ramsey
sophia-ramsey deleted the sramsey/csharp-void-success branch September 14, 2026 20:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants