Azure / Azure-Functions

1.1k stars 189 forks source link

CreatedResult in .NET 8 does not return status code 201 #2475

Closed thomaseyde closed 3 weeks ago

thomaseyde commented 2 months ago
  1. Create a new .NET 8 Function App
  2. Create an HTTP trigger function and name it PostCreated
  3. Remove the "post" method (optional)
  4. Change return type to IActionResult
  5. Return new CreatedResult()
  6. Test by calling POST http://localhost:7071/api/PostCreated
  7. Observe that the status code is 204, not 201

Decompiled code shows that the default constructor passes null to its base and does not initialize the StatusCode property. I suspect this causes the default return value to be returned.

Decompiled code:

[Microsoft.AspNetCore.Mvc.Infrastructure.DefaultStatusCode(201)]
public class CreatedResult : ObjectResult
{
  private const int DefaultStatusCode = 201;
  #nullable disable
  private string _location;

  /// <summary>
  /// Initializes a new instance of the <see cref="T:Microsoft.AspNetCore.Mvc.CreatedResult" /> class
  /// </summary>
  public CreatedResult()
    : base((object) null)
  {
  }

  // ...
}

NuGet packages:

    <ItemGroup>
        <PackageReference Include="AzureFunctions.Worker.Extensions.AspNetCore" Version="1.0.10" />
        <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.22.0" />
        <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.1.0" />
        <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.17.2" />
    </ItemGroup>

Http trigger:

public class PostCreated
{
    [Function("PostCreated")]
    public IActionResult Run(
        [HttpTrigger(AuthorizationLevel.Function, "post")]
        HttpRequest req,
        FunctionContext executionContext
        )
    {
        return new CreatedResult(); // Returns 204 No Content
    }
}
bhagyshricompany commented 2 months ago

Thanks for reporting will check and update.

bhagyshricompany commented 1 month ago

@fabiocav pls comment and validate.

bhagyshricompany commented 1 month ago

Hi @thomaseyde I checked and found its returning proper status code can you check that again.

public class PostCreated
{
    [Function("PostCreated")]
    public IActionResult Run(
        [HttpTrigger(AuthorizationLevel.Function, "post")]
    HttpRequestData req,
        FunctionContext executionContext)
    {
        return new CreatedResult("", null); // Return a new CreatedResult with status code 201
    }
}
image
thomaseyde commented 1 month ago

@bhagyshricompany your code example is not the same as mine. You call a different constructor which, most likely, does different work.

bhagyshricompany commented 4 weeks ago

yes as i tries with your code on that staus code is 201but that is api properties not coming cause of azure function.