简体   繁体   中英

.NET 6 - How to use Optional Route Parameters ASP.NET Core WEB API?

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?}")]
public class XYZController : ControllerBase
{
    [HttpPost]
    public string PostAsync(int customerId)
    {
        return JsonSerializer.Serialize("Sample");
    }
}

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

在此处输入图像描述

How should I address this?

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("{customerId}"]
    public string PostAsync(int customerId)
    {
        return JsonSerializer.Serialize("Sample");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM