Lars Holdgaard Lars Holdgaard - 5 months ago 18
C# Question

Custom route in web api just redirects to current page

Being a noob in MVC web api there is probably something very obvious I'm missing..

However, In my

ProjectController
I have the following method with attributes (I know this kind of method should be POST but just testing easily...):

[Route("api/projects/archive/{id:int}")]
[HttpGet]
public void Archive(int id)
{
_projectService.Archive(id);
}


However, when I open my URL such as:

http://localhost:49923/api/projects/archive/1


The page simply redirects to the current URL, and the archive method is not called. I also have a breakpoint at the method to verify it's not hit.

My best guess is I also have to update my web api route config which is the default, but I just assumed the route attribute was enough?

Here is my web api route config:

public static void Register(HttpConfiguration config)
{
// Web API configuration and services

// Web API routes
config.MapHttpAttributeRoutes();

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

config.Formatters.JsonFormatter.SupportedMediaTypes
.Add(new MediaTypeHeaderValue("text/html"));

}


What am I doing wrong here? :-)

EDITS:

Clearification 1 - my ProjectController:

public class ProjectsController : ApiController
{

private ProjectService _projectService;

public ProjectsController()
{
_projectService = new ProjectService();
}

[Route("api/projects/archive/{id:int}")]
[HttpGet]

public void Archive(int id)
{
_projectService.Archive(id);
}
}


Clearification 2 - redirect:

So lets say I stand on the homepage (/). I then go to the URL "
http://localhost:49923/api/projects/archive/1
", it will just reload page and leave my back at the home page.

Answer Source

The Web API config is configured correctly. Ensure that the controller and the action are constructed properly

public class ProjectController : ApiController {

    //...other code removed for brevity

    [HttpGet]
    [Route("api/projects/archive/{id:int}")]//Matches GET api/projects/archive/1
    public IHttpActionResult Archive(int id) {
        _projectService.Archive(id);
        return Ok();
    }    
}