Home > front end >  How to add suffix on API Endpoints .NET Core
How to add suffix on API Endpoints .NET Core

Time:03-02

Is there a way to automatically add a suffix on all endpoint routes e.g .json.

v1/users.json
v1/users/{id}.json

so what I have tried so far is I created a BaseController which look like this

[ApiController]
[Route("v1/[controller].json")]
public class BaseController : ControllerBase
{
}

but every time I use it to my controller it looks like this

v1/users.json
v1/users.json/{id}

CodePudding user response:

You can add extra routing to the actual endpoints rather than the controllers

[ApiController]
[Route("v1/[controller]")]
public class BaseController : ControllerBase
{
    [HttpGet(".json")]
    public IActionResult Get()
    {
    
    }
    
    // Without Route Parameters
    [HttpGet("{id}.json")]
    public IActionResult Get([FromRoute] int id)
    {
          ...
    }

    // With Route and Query Parameters
    [HttpGet("{id}.json/friend")]
    public IActionResult Get([FromRoute]int id,[FromQuery] string friendName)
    {
          ...
    }

    // With Route and Query Parameters and Body
    [HttpPost("{id}.json/friends")]
    public IActionResult Get([FromRoute]int id,[FromQuery] string message, [FromBody]IFilter filter)
    {
          ...
    }
}

CodePudding user response:

You could use the URL Rewriting Middleware to accept URLs with .json and then simply remove it. So something like:

/api/users/123/picture.json?query=123

would become:

/api/users/123/picture?query=123

You can do this by adding the following code to your Startup's Configure method:

var rewriteOptions = new RewriteOptions()
    .AddRewrite(@"^(.*?)(?:\.json)(\?.*)?$", "$1$2");
app.UseRewriter(rewriteOptions);

See the docs for more information.

Caveat: If you use Url.Action(...), etc. to generate a URL within code, then it won't include .json. The rewrite only affects incoming requests.

  • Related