2

Let me give an example of my problem, I have registered my routes as following(RouteConfig.cs):

routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

if you look at my controller, it has the following function;

[Route("all")]
public HttpResponseMessage Get(HttpRequestMessage request)
{
    return CreateHttpResponse(request, () =>
    {
        HttpResponseMessage response = null;
        var HolidayCalendars = _holidayCalendarsRepository.GetAll().ToList();
        IEnumerable<HolidayCalendarViewModel> holiVm = Mapper.Map<IEnumerable<HolidayCalendar>, IEnumerable<HolidayCalendarViewModel>>(HolidayCalendars);
        response = request.CreateResponse<IEnumerable<HolidayCalendarViewModel>>(HttpStatusCode.OK, holiVm);

        return response;
    });
}

up to this point everything is going great. My page loads with the requested data. Now, when I go and add another function, for example;

[Route("allHolidays/{id:int}")]
public HttpResponseMessage GetHolidays(HttpRequestMessage request, int id)
{
    return CreateHttpResponse(request, () =>
    {
        HttpResponseMessage response = null;
        HolidayCalendar Calendar = _holidayCalendarsRepository.GetSingle(id);
        var Holidays = Calendar.Holidays.OrderBy(s => s.HolidayDate).ToList();
        IEnumerable<HolidayViewModel> holidayVm = Mapper.Map<IEnumerable<Holiday>, IEnumerable<HolidayViewModel>>(Holidays);

        response = request.CreateResponse<IEnumerable<HolidayViewModel>>(HttpStatusCode.OK, holidayVm);

        return response;
    });
}

I will get the following error in my webpage;

Failed to load resource: the server responded with a status of 400 (Bad Request)

Strange thing is, my request did not change, there is only a new Controller in my api.

This should not be happening because my code is requesting different routes, for example;

function loadData() {
    apiService.get('/api/HolidayCalendars/all', null,
                HolidayCalendarLoadCompleted,
                HolidayCalendarLoadFailed);
}

or

function loadData() {
    apiService.get('/api/HolidayCalendars/allHolidays?id=' + $routeParams.id, null,
                HolidaysLoadCompleted,
                HolidaysLoadFailed);
}

Any ideas?

constructor class WebApiConfig:

public static void Register(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();
    config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new {id = RouteParameter.Optional }
    );
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472
Brian
  • 41
  • 7

4 Answers4

0

Your route for allHolidays implies this format

/api/HolidayCalendars/allHolidays/123

According to your route attribute

[Route("allHolidays/{id:int}")]

But you've passed the id as a querystring parameter

api/HolidayCalendars/allHolidays?id=123
Jamiec
  • 133,658
  • 13
  • 134
  • 193
0

Looks like you're using AttributeRouting (http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2) on the Controllers :

[Route("all")]

but you're using standard routing in the config:

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

Try activate the AttributeRouting with:

configuration.MapHttpAttributeRoutes();

where configuration is the actual instance of HttpConfiguration.

Luca Ghersi
  • 3,261
  • 18
  • 32
  • I forgot to inlude my WebApiConfig Class, i will add it now. In there i added the configuration.MapHttpAttributeRoutes(); – Brian Mar 15 '16 at 15:08
0

The issue is in your WebApiConfig. In the routeTemplate, you haven't specified an action.

routeTemplate: "api/{controller}/{id}",

If I remember correctly, this is the default config for WebAPI. It filters requests on a controller by verb. That's why when you call

apiService.get('/api/HolidayCalendars/all'.....)

It returns the Get() method on your HolidayCalendars controller.

To fix the issue, add the {action} parameter to your routeTemplate:

public static void Register(HttpConfiguration config)
    {
config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new {id = RouteParameter.Optional }
            );
}
  • Thank you for your reaction, but when i add the {action} statement i get a 404 on all my functions. (Failed to load resource: the server responded with a status of 404 (Not Found)) Also, i think my RouteConfig specifies this. (See my first codeblock). – Brian Mar 16 '16 at 07:21
  • Ok, a couple of other ideas... Remove the routing attribute and try to make the call. Next, try adding a `[HttpGet]` attribute. If either of those don't work, the issue may be how you're passing your parameters to the method. Update your method signature to `GetHolidays([FromBody]HttpRequestMessage request, int id)` and give it a try. – Jeremy Waller Mar 16 '16 at 13:10
0

I finally found the solution!

At the top of my code i had a reference to System.Web.Mvc. This way the routing and RESTful functions were not interpreted as it should in a web Api. This caused some strange functioning in my app.

Solution:

Change

using System.Web.Mvc;

To

using System.Web.Http;

This evaded me for three days,until I came along the following answer: https://stackoverflow.com/a/21999235/6033193

Community
  • 1
  • 1
Brian
  • 41
  • 7