There are 2 WebAPI routes,in .NET core 2.2
1)[Delete] /Employees
2) [Delete] /Employees/{EmpID}
When EmpID is null or empty instead of 2nd route first route is triggering. I need the 2nd route /Employees/{EmpID} to trigger when route is "/Employees/" and 1st route to trigger when /Employees is invoked.
But in .NET core webapi in bot cases "/Employees" and "/Employees/" triggering the same route /Employees.
How is it possible to trigger 2nd route when "/Employees/" is invoked.How to resolve the conflict with and without /
I need the 2nd route /Employees/{EmpID} to trigger when route is "/Employees/" and 1st route to trigger when /Employees is invoked.
You could use URL Rewriter to rewrite the request path.Refer to my below demo where EmpID
is int
type.
1.Create Rules
public class RewriteRuleTest : IRule
{
public void ApplyRule(RewriteContext context)
{
var request = context.HttpContext.Request;
var path = request.Path.Value;
if (path.ToLower() == "/employees/")
{
context.HttpContext.Request.Path = "/employees/0";
}
}
}
2.Add the middleware in startup Configure
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseRewriter(new RewriteOptions().Add(new RewriteRuleTest()));
app.UseMvc();
}
3.Test action
[HttpDelete("/Employees/{EmpID}")]
public void DeleteOne(int empID)
{
if (empID == 0)
{
//for the condition when empID is null or empty
}
else
{
//for the condition when empID is not null or empty
}
}
[HttpDelete("/Employees")]
public void Delete()
{
}