让我举例说明我的问题, 我已将我的路线注册如下(RouteConfig.cs):
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
如果你看一下我的 Controller ,它有以下功能;
[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);
}
有什么想法吗?
构造类 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
关于javascript - 一个 Controller 中的多个路由导致 400 :bad request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36014629/