G.Anıl Yalçın
G.Anıl Yalçın

Reputation: 188

Url Rewriting in Asp.Net core 3.0

In .Net Core web API I want the endpoints to work with both ways like : /api/order or /order

So I tried so many regex patterns for rewriting the url to except "api" but no luck yet. In startup Configure :

var rewrite = new RewriteOptions()
       .AddRewrite("^(?!api\\/).*$", "/api/$1", true)
       .AddRedirectToHttps();
 app.UseRewriter(rewrite);

I believe my approach could be wrong about this.

Order Controller:

    [Route("api/[controller]")]
    [ApiController]
    public class OrderController : ControllerBase
    {

Upvotes: 3

Views: 1711

Answers (2)

G.Anıl Yalçın
G.Anıl Yalçın

Reputation: 188

After so many tries, I've found the answer. If only Regex could be a bit easier.

.AddRewrite("^(?!api\\/)(.*)$", "api/$1", true)

.* needed to be in brackets and rewrite value did not need a preceeding forward slash.

Regex examples in this article made me find my own way.

In order to understand what goes behind the rewriter I needed to add another middleware to log incoming http requests. Here is a good article for that.

Upvotes: 1

Aydin
Aydin

Reputation: 15294

Why not just use two Route attributes instead of that single one...

[Route("api/[controller]")]
[Route("[controller]")]
public class OrderController : ControllerBase

Will work, you could even setup a base controller class with those attributes and never have to deal with it again (I think)

Upvotes: 1

Related Questions