Asp.net mvc route restriction

This is my route configuration:

routes.MapRoute(
            name: "AdsCategories",
            url: "Ads/{key}",
            defaults: new { controller = "Ads", action = "Index" },
            //constraints: new { key =  },
            namespaces: new string[] { "Vprok.Controllers" }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            namespaces: new string[] { "Vprok.Controllers"}
        );

How to create an "AdsCategories" restriction? I need to use the default route if the action in the "Ads" controller == {key}.

+4
source share
2 answers

So basically, if {key}is an existing action that you want it to be handled by the default route instead of using the action Indexon the controller Ads?

To achieve this, you can list all the possible actions in a key constraint:

routes.MapRoute(
    name: "AdsCategories",
    url: "Ads/{key}",
    defaults: new { controller = "Ads", action = "Index" },
    constraints: new { key = @"^create|update|delete" },
    namespaces: new string[] { "Vprok.Controllers" }
);

AdsCategories URL ads/create ads/update ads/delete. , ads/foobar .

+9

:

routes.MapRoute(
            name: "AdsCategories",
            url: "Ads/{key}",
            defaults: new { controller = "Ads", action = "Index" },
            //constraints: new { key =  },
            namespaces: new string[] { "Vprok.Controllers" }
        );

actionresult id!

+1

Source: https://habr.com/ru/post/1524071/


All Articles