How to combine pattern and attribute based routing in ASP.NET Core?

I need to define pattern-based routing for the controller, and then an action-based attribute in ASP.NET Core. Sort of:

public class Foo : Controller
{
    [HttpGet]
    public object Get()
    {
        return new
        {
            ID = "A"
        };
    }

    [HttpPost]
    public object Create([FromBody]dynamic entity)
    {
        return new
        {
            ID = "B"
        };
    }


}

Route

app.UseMvc(routes =>
        {
            routes.MapRoute("Settings", "settings/api/foo",
                    new { controller = "Foo" }
            );
        });

And I expect this to work:

GET /settings/api/foo
POST /settings/api/foo

Unfortunately, this is not the case. It appears that route attributes are ignored. What is the best way to achieve the requirement?

+4
source share
1 answer

The trick here is to direct the URL to a specific controller and action. Then use the action method overload with the action method switch to switch between GET and POST.

Change the route setup code to this:

app.UseMvc(routes =>
{
    routes.MapRoute(
        "Settings",
        "settings/api/foo",
        new {
            controller = "Foo", // specific controller
            action = "DoThing", // AND specific action
        }
    );
});

( - HTTP-) , :

public class FooController : Controller
{
    [HttpGet] // different action method selector!
    public object DoThing() // same name!
    {
        return new
        {
            ID = "A"
        };
    }

    [HttpPost] // different action method selector!
    public object DoThing([FromBody]dynamic entity) // same name!
    {
        return new
        {
            ID = "B"
        };
    }
}

MVC URL DoThing Foo. , : ", , , , !" [HttpGet] [HttpPost], , , , .

0

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


All Articles