Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use the more typesafe way of returning action results in controllers #40

Open
vvdb-architecture opened this issue Oct 12, 2022 · 0 comments

Comments

@vvdb-architecture
Copy link
Contributor

The guidance generates something like this:

    [ServiceAspect(Access.AccessApplication)]
    [ProducesResponseType(typeof(EnvironmentInfo), StatusCodes.Status200OK)]
    [HttpGet("")]
    public async Task<IActionResult> GetAsync()
    {
        return Ok(await EnvironmentInfoBL.GetEnvironmentInfoAsync());
    }

Several things can noticed:

  • the HttpGet attribute serves no purpose and can be eliminated
  • the return value Task<IActionResult> is untyped. You can return anything and it only will show at runtime if you're right or wrong.
  • as a result of the untyped return value, you need to specify it explicitly in ProducesResponseType but there again you can specify anything since there is no verifyable relation between the attribute and the actual return value it is decorating.

A more modern and secure way of writing is this:

    [ServiceAspect(Access.AccessApplication)]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public async Task<ActionResult<EnvironmentInfo>> GetAsync()
    {
        return await EnvironmentInfoBL.GetEnvironmentInfoAsync();
    }

The generated Swagger code is exactly the same. No more explicit Ok() since it's the default (but you still can return other things like NotFound()). The ProducesResponseType deduces the actual type from the return value of the method.

Type conversion is implicit for all non-interface types. See https://learn.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-6.0#actionresultt-type-1 for more information.

It would also be good practice to systematically include a CancellationToken on the async methods, but in this particular instance it isn't used in the implementation.

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

No branches or pull requests

1 participant