Skip to content

Add Forbidden and Forbidden<T> HttpResults like Ok/NotFound/Conflict and others #64775

@ntark

Description

@ntark

Background and Motivation

In order to return Forbidden or Forbidden from my minimal API endpoint with Results<....> return type, I have to add a bunch of code to each repository.
It's not really a blocker but having to then maintain each copy in different repositories is not ideal.
personal nuget package also does not feel too nice for something I believe should be part of ASP.NET.

Proposed API

Add Forbidden.cs:

namespace Microsoft.AspNetCore.Http.HttpResults;

public sealed class Forbidden : IResult, IEndpointMetadataProvider, IStatusCodeHttpResult
{

}

Add ForbiddenOfT.cs:

namespace Microsoft.AspNetCore.Http.HttpResults;

public sealed class Forbidden<TValue> : IResult, IEndpointMetadataProvider, IStatusCodeHttpResult, IValueHttpResult, IValueHttpResult<TValue>
{

}

Add two methods to TypedResults.cs

namespace Microsoft.AspNetCore.Http;

public static class TypedResults
{
    public static Forbidden<T> Forbidden<T>(T? value = default) => new(value);
    public static Forbidden Forbidden() => new();
}

Usage Examples

public static class GetUser
{
    public static void MapGetUserEndpoint(this IEndpointRouteBuilder app)
    {
        app.MapGet("/users/{userId}", GetUserAsync);
    }

    public static async Task<Results<Ok<User>, Forbidden<string>>> GetUserAsync(
        [FromServices] IUserService _userSevice, long userId)
    {
        var user = await _userSevice.GetUserByIdAsync(userId);

        return user is not null
            ? TypedResults.Ok(user)
            : TypedResults.Forbidden<string>("User not found");
    }
}

Alternative Designs

I don't think there is room for alternative since other response types are already so much alike (Ok/NotFound/Conflict).

Risks

Might spark confusion between existing Forbid result and ones proposed here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-minimalIncludes minimal APIs, endpoint filters, parameter binding, request delegate generator etc

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions