一个控制器中的多个路由导致 400:bad 请求

multiple routes in one controller causes 400:bad request

让我举例说明我的问题, 我已将我的路线注册如下(RouteConfig.cs):

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

如果你看看我的控制器,它有以下功能;

[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;
    });
}

到目前为止,一切都很顺利。我的页面加载了请求的数据。现在,当我去添加另一个功能时,例如;

[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;
    });
}

我的网页会出现以下错误;

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

奇怪的是,我的要求没有改变,我的api里只有一个新的Controller。

这不应该发生,因为我的代码正在请求不同的路由,例如;

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

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

有什么想法吗?

构造函数class WebApiConfig:

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

allHolidays 的路线暗示了这种格式

/api/HolidayCalendars/allHolidays/123

根据你的路由属性

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

但您已将 id 作为查询字符串参数传递

api/HolidayCalendars/allHolidays?id=123

看起来您正在控制器上使用 AttributeRouting (http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2) :

[Route("all")]

但您在配置中使用标准路由:

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

尝试激活 AttributeRouting:

configuration.MapHttpAttributeRoutes();

其中配置是 HttpConfiguration 的实际实例。

问题出在您的 WebApiConfig 中。在 routeTemplate 中,您尚未指定操作。

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

如果我没记错的话,这是 WebAPI 的默认配置。它通过动词过滤控制器上的请求。这就是为什么当你打电话给

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

它 returns HolidayCalendars 控制器上的 Get() 方法。

要解决此问题,请将 {action} 参数添加到您的 routeTemplate:

public static void Register(HttpConfiguration config)
    {
config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new {id = RouteParameter.Optional }
            );
}

我终于找到了解决办法!

在我的代码顶部,我引用了 System.Web.Mvc。这样,路由和 RESTful 函数就不会像在 Web Api 中那样被解释。这导致我的应用出现一些奇怪的功能。

解决方案:

改变

using System.Web.Mvc;

using System.Web.Http;

这让我躲了三天,直到我得出以下答案: