3

I have created an ASP.NET Core WEB API template project and targeting .NET 6.

I have the following controller code,

using System.Text.Json;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace abc.Controllers;

[Authorize]
[ApiController]
[Route("api/v{version:apiVersion}/customers/{customerId?}/something")]
public class XYZController : ControllerBase
{
    [HttpPost]
    public string PostAsync(int customerId)
    {
        return JsonSerializer.Serialize("Sample");
    }
}

In the Swagger UI, I still see customerId as required,

enter image description here

How should I address this?

1
  • This is a common problem found in swagger (see stackoverflow.com/questions/46510901/… and other places). The quickest fix would be to remove {customerId} from your route. Swagger will pick it up from the method signature but it wont be mandatory. Commented Aug 11, 2022 at 22:44

1 Answer 1

6

you don't use route input parameters for a controller route, only for an action

[Route("~/api/v{version:apiVersion}/customers")]
public class XYZController : ControllerBase
{
    [HttpPost("something")] 
    [HttpPost("{customerId}/something")] 
    public string PostAsync(int? customerId)
    {
        return JsonSerializer.Serialize("Sample optional");
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Does it make customerId parameter optional?
@tRuEsAtM you can make it optional for an action where it is needed.
endpoints.MapControllers() require me add UseRouting() and it is messing up my endpoint URL to https://localhost:7075/rc/api/v1/customers/Post/1 I want to have a single endpoint/method which takes an optional param, and my route should remain unchanged. For e.g. using postman https://localhost:7075/rc/api/v1/customers/1/something and https://localhost:7075/rc/api/v1/customers/something I want to achieve the same results. Is it possible?
@tRuEsAtM You have to update your question. Now you are asking about completely different thing. As I understand now you want to place id in the middle of the url, not at the end.
My bad, I updated the question, yeah I need the Id in the middle.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.