MorgoZ
MorgoZ

Reputation: 2052

generate url with Url.Action helper from attribute routing controller with prefix

i have definned a Map route like this:

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

and i have an API Action with Attribute routing like this:

[Route("api/User")]
public class UserApiController : Controller
{
    ....
    [HttpGet]
    [Route("Teacher")]
    public async Task<IEnumerable<UserApiVM>> GetTeachers()
    {
        ....
    }
 }

Which i can access browsing to a direct url like "http://api/User/Teacher".

Now i whant to generate that url using the @URL.Action helper or any other helper, but i can't figure out how. I tried with

@Url.Action("Teacher","UserApi")

but it couldn't find the controller.

BTW, the controller is Controllers are in a folder called "Controllers", and the API controllers in a folder called "API" inside the "Controllers" folder.

Thanks!

Upvotes: 0

Views: 783

Answers (1)

Edward
Edward

Reputation: 29966

For generating api/User/Teacher, you need to specify GetTeachers as controller name instead of Teacher.

@Url.Action("GetTeachers", "UserApi")

If you want to generate URL by specifying Teacher, you could try to set route name like below:

    [HttpGet]
    [Route("Teacher",Name = "Teacher")]
    public async Task<IEnumerable<string>> GetTeachers()
    {
        return null;
    }

And generate URL by:

@Url.RouteUrl("Teacher")

Upvotes: 2

Related Questions