Home > Mobile >  ASP.NET Core: Default value for Guid parameter in web api?
ASP.NET Core: Default value for Guid parameter in web api?

Time:12-02

Is it possible to provide a default value to a Guid parameter in an ASP.Net core (.net 7) web api?

Like this:

[HttpGet()]
public async Task<ActionResult<Foo>> PostSomething(Guid tenantId = "21c10283-6db0-489b-94d0-f0b3969fc799") // <<-- invalid of course

So far I'm using an optional parameter and assigning the default value in the method, but I'd like to expose it in the signature if possible.

public async Task<ActionResult<Foo>> PostSomething(Guid? tenantId) 
{
   tenantId ??= Guid.Parse("21c10283-6db0-489b-94d0-f0b3969fc799");

Note: Other answers show how to set an empty default value, but thats not what I need here.

// Edit: If this is not possible at all, thats also an answer. But please read the question carefully before posting anything.

CodePudding user response:

Although you cannot expose the default value in the signature, you can set it using the DefaultValueAttribute, which is picked up by Swashbuckle and presumably other tooling.

Here's an example:

private const string defaultTenantId = "21c10283-6db0-489b-94d0-f0b3969fc799";

[HttpGet]
public async Task<ActionResult<Foo>> PostSomething(
    [DefaultValue(defaultTenantId)] Guid? tenantId) 
{
   tenantId ??= Guid.Parse(defaultTenantId);

   // ...
}

CodePudding user response:

// define your default or take it from somewhere
static Guid defaultGuid = Guid.Parse("21c10283-6db0-489b-94d0-f0b3969fc799");

// use this function to get your guid
public static Guid GetGuidOrDefault(Guid? guid) => guid ?? defaultGuid;

public async Task<ActionResult<Foo>> PostSomething(Guid? tenantId) 
{
    // but it is extremely wrong to change the values of function parameters
    tenantId = GetGuidOrDefault(tenantId);

CodePudding user response:

how about with tenantId ??= default(Guid);?

you can also use for other datatypes like string, etc.

  • Related