Pancake
Pancake

Reputation: 865

How can I make Url.Action() recognize areas defined in referenced Razor Class Libraries?

In my ASP.NET Core project's Razor, I'm using Url.Action() like this:

@Url.Action("Index", "Foo", new {Area = "MyArea"})

The controller action is defined in a referenced Razor Class Library like so:

[Route("MyArea/Foo")]
[Authorize]
public class FooController : Controller
{

    [HttpPost]
    public IActionResult Index()
    {
        return Ok();
    }

}

Back in my ASP.NET Core project, in the Visual Studio code editor, MyArea appears in red, and the hover tooltip states "Cannot resolve area 'MyArea'". And of course, my call to Url.Action() returns string.Empty....

But the route is valid.

What change(s) could I apply to either my ASP.NET Core project or the referenced RCL to cause MyArea to be recognized as a valid area, and make the call Url.Action() return the expected URL?

Upvotes: 0

Views: 342

Answers (1)

mvermef
mvermef

Reputation: 3914

[Area("MyArea")]
[Authorize]
public class FooController : Controller
{

    [HttpPost]
    public IActionResult Index()
    {
        return Ok();
    }

}

Areas are different part of the route since they are named.. So you have to use the [Area()] otherwise it doesn't know what you are asking for the route. By convention the Foo route is already know since it's the name of the controller. This assumes you have the route mapped correctly in the Configure() method in your startup.cs. This also assumes that you are using the Area folder with a folder called MyArea in it.

https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/areas?view=aspnetcore-3.1

Upvotes: 0

Related Questions