0

I am using Visual Studio 2017..... when I created the project, an AccountController was created with this action:

    // POST api/Account/Logout
    [Route("Logout")]
    public IHttpActionResult Logout()
    {
        Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);
        return Ok();
    }

On the other hand, this route was created by default:

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

I need to do a very simple thing. How can I get the Logout URL in a view?

I tried

@Url.Action("Logout", "Account", new { httproute = "DefaultApi" })

But it did not work since DefaultApi does not contain the action, causing the action to be added as a query string parameter.

If I don't use httproute property, the URL is built but without the "api" part causing the framework to not find it.

I have even tried

@Url.RouteUrl("DefaultApi", new { httproute = "Logout", controller = "Account" })">

with no success either.

jstuardo
  • 3,901
  • 14
  • 61
  • 136
  • How about using `@Url.HttpRouteUrl()`? I see that you're not tried this helper before, see related issue here: https://stackoverflow.com/questions/19868148/how-do-i-generate-a-webapi-url-from-an-mvc-view. Also make sure that the routes are in proper order. – Tetsuya Yamamoto Nov 21 '18 at 01:41

1 Answers1

0

You can define a new route to define your action name:

routes.MapHttpRoute(
    name: "ActionApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

If you don't include the action name, Web API tries to find a suitable action for you based on your HTTP verb... for example if you send a Get request Web API tries to find an action starting with 'Get'... since your action name is Logout, the default API routing convention cannot match it to a request. see here for more info

Then this link should call the action (see here):

@Url.HttpRouteUrl("ActionApi", new {controller = "Account", action = "Logout"})
Hooman Bahreini
  • 14,480
  • 11
  • 70
  • 137