gpt4 book ai didi

c# - 找不到与请求 URI 匹配的 HTTP 资源 - Web API + Angular

转载 作者:行者123 更新时间:2023-11-30 18:18:13 26 4
gpt4 key购买 nike

当我尝试从 Web API 获取一些带有参数(类型 DateTime)的数据时,我收到错误 404 的响应:

Message : "No HTTP resource was found that matches the request URI 'http://localhost:53544/api/reservations/GetReservationByDate?date=Tue Jan 31 2017 16:00:00 GMT+0100'." MessageDetail : "No route providing a controller name was found to match request URI 'http://localhost:53544/api/reservations/GetReservationByDate?date=Tue Jan 31 2017 16:00:00 GMT+0100'"

我为此使用 AngularJS。在其他 Controller 中,我有带参数的方法,但没有 DateTime。这可能是问题吗?在此之前我有错误

400 Bad Request

配置路由对我有帮助。

这都是我的代码 - Controller 中的方法:

[HttpGet]
[ActionName("GetReservationByDate")]
[ResponseType(typeof(Reservation))]
public IHttpActionResult GetReservationByDate(DateTime date)
{
var reservation = db.Reservations.Where(d => d.Date.Equals(date));
if (reservation == null)
{
return NotFound();
}
return Ok(reservation);
}

路由配置文件:

config.Routes.MapHttpRoute(
name: "CustomApi",
routeTemplate: "api/Reservations/GetReservationByDate/{date}",
defaults: new { date = RouteParameter.Optional}
);

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

和来自 AngularJS 的方法:

this.GetReservation = function (date) {
var promise = $http({
method: 'GET',
url: 'api/reservations/GetReservationByDate?date=' + date,
config: {
params: {
"date": date
}
}
})
.then(function (response) {
return response;
},
function (response) {
return response;
});
return promise;
}

我尝试了不同的组合,使用 FromUriFromBody,但结果总是一样。

最佳答案

您需要为 Controller 和操作设置默认值,因为路由模板中不包含模板参数。

config.Routes.MapHttpRoute(
name: "CustomApi",
routeTemplate: "api/Reservations/GetReservationByDate/{date}",
defaults: new { controller = "Reservations", action = "GetReservationByDate", date = RouteParameter.Optional}
);

更新操作以允许错误数据

[HttpGet]
[ActionName("GetReservationByDate")]
[ResponseType(typeof(Reservation))]
public IHttpActionResult GetReservationByDate(DateTime? date) {
if(date.HasValue) {
var reservation = db.Reservations.Where(d => d.Value.Date.Equals(date)).ToList();
if (reservation.Count == 0) {
return NotFound();
}
return Ok(reservation);
}
return BadRequest();
}

同时尝试格式化客户端的日期以确保它以正确的格式发送

this.GetReservation = function (date) {
var jsonDate = date.toJSON();
var promise = $http({
method: 'GET',
url: 'api/reservations/GetReservationByDate?date=' + jsonDate,
config: {
params: {
"date": jsonDate
}
}
})
.then(function (response) {
return response;
},
function (response) {
return response;
});
return promise;
}

关于c# - 找不到与请求 URI 匹配的 HTTP 资源 - Web API + Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41970278/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com