GomuGomuNoRocket
GomuGomuNoRocket

Reputation: 839

Routing where one of parameter values is part of URL path

I am confused with routing in Asp.Net core 1 and I need help. In startup.cs I have this configuration

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");      
});

I have created a controller 'Entities' and a method 'Get'

[Authorize]
public class EntitiesController : Controller
{                    
    [Produces("text/html")]
    public string Get(string entity, string type)
    {            
        return "<html><body>test</body></html>";
    }

}

So, when I text in url link like below works

http://localhost:12895/Entities/Get?entity=entity&type=type

and function called with params.

But I want to change this url and keep same functionality. I want my url become

http://localhost:12895/Entities/entity?type=type

so, only type will be parameter and the name of entity will change for example

http://localhost:12895/Entities/human?type=type

http://localhost:12895/Entities/dog?type=type

but invoke the same function.

Is this possible?

Upvotes: 1

Views: 324

Answers (1)

Eugene Voynov
Eugene Voynov

Reputation: 350

There's full info about .net core routings.

Yes. It is possible. Add an additional route in app.UseMvc for your class.

It should looks like a

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}"
    );      


    routes.MapRoute(
        name: "entities",
        template: "Entities/{entity}",
        defaults: new { controller = "Entities", action = "Get"}
    );
});

Upvotes: 2

Related Questions