briddums
briddums

Reputation: 1846

Attribute routing - can I specify default values for parameters not in the route

I have an action which returns a file. It can either open it in the user's browser or download it directly to their PC.

public async Task<IActionResult> Open(int Id, bool Download)
{
    ....
}

Via conventional routing I can define routes for downloading vs opening the file:

// Download the file
routes.MapRoute(
    name: "FileDownload",
    template: "File/Download/{id}",
    defaults new { controller "File", action = "Open" download = true });     

// Open file in browser
routes.MapRoute(
    name: "FileView",
    template: "File/View/{id}",
    defaults new { controller "File", action = "Open" download = false }); 

I am thinking of switching to attribute based routing. I was wondering if there is any way to specify a default for the download parameter when it's not part of the route path.

[Route("[File/View/{id}", Name="FileView")]
[Route("[File/Download/{id}", Name="FileDownload")]    

Upvotes: 0

Views: 52

Answers (1)

M&#233;toule
M&#233;toule

Reputation: 14472

I'm not sure if it's directly possible, but why not simply use overloading?

You'll have something like this:

[Route("[File/View/{id:int}", Name="FileView")]
public async Task<IActionResult> View([FromRoute] int id)
{
    return await Open(id, false);
}

[Route("[File/Download/{id:int}", Name="FileDownload")]
public async Task<IActionResult> Download([FromRoute] int id)
{
    return await Open(id, true);
} 

private async Task<IActionResult> Open(int Id, bool Download)
{
    ....
}

Upvotes: 1

Related Questions