webapi调用返回错误:
message: "No HTTP resource was found that matches the request URI 'http://localhost:25396/api/dmpe/form/123'.",
messageDetail: "No action was found on the controller 'Dmpe' that matches the request."
控制器:
[HttpGet]
[ActionName("GetForm")]
public HttpResponseMessage GetForm(long formId)
{
try
{
var form = this.dmpeService.GetForm(formId);
return Request.CreateResponse(HttpStatusCode.OK, form);
}
catch (Exception e)
{
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(new { success = false, message = e.Message });
_logger.Error("GetForm Error: {0}", e.Message);
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, json);
}
}
WebApi路线配置:
//config.Routes.MapHttpRoute(
// name: "GetForm",
// routeTemplate: "api/dmpe/form/{id}",
// defaults: new
// {
// controller = "Dmpe",
// action = "GetForm"
// }
// );
更新路线:
config.Routes.MapHttpRoute(
name: "GetForm",
routeTemplate: "api/{controller}/form/{id}"
);
我根据当前的命名惯例建立了路线。这条路线有效。
config.Routes.MapHttpRoute(
name: "GetMenu",
routeTemplate: "api/forms/menu/{userTypeId}/{ctyhocn}",
defaults: new
{
controller = "Service",
action = "GetMenu"
},
constraints: new { httpMethod = new HttpMethodConstraint(new[] { HttpMethod.Get.ToString() }) }
);
现在在WebApi v2中,我已经习惯于在控制器中定义路由,如下所示,但这是我发现的v2功能。根据当前的例子,我认为routeTemplate可以工作。我查看了我定义的路线的RouteTables.Routes,它看起来格式正确:“api / {controller} / form / {id}”
WebApi v2路由属性
[HttpGet]
[AllowAnonymous]
[Route("api/office/companynames/{searchValue}/")]
.....
答案 0 :(得分:0)
您获得的错误消息与路由的配置方式有关,而与Ninject无关。 WebAPI(1.0或2.2)的良好实践是使用以下模板:
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
与MVC不同,没有包含操作名称。
因此,尝试使用路线设置来查看是否可以让它工作。
答案 1 :(得分:0)
@Karen_B向我指出了正确的方向,但我想提供适用于其他人遇到的更改。
我将路线映射更改为:
config.Routes.MapHttpRoute(
name: "NewForm",
routeTemplate: "api/{controller}/form/",
defaults: new
{
controller = "Dmpe"
},
constraints: new { httpMethod = new HttpMethodConstraint(new[] { HttpMethod.Post }) }
);
config.Routes.MapHttpRoute(
name: "GetForm",
routeTemplate: "api/{controller}/form/{id}",
defaults: new
{
controller = "Dmpe",
id = RouteParameter.Optional
},
constraints: new { httpMethod = new HttpMethodConstraint(new[] { HttpMethod.Get }) }
);
然后将控制器更改为:
[HttpPost]
public HttpResponseMessage Post(DmpeForm form)
{
....
[HttpGet]
public HttpResponseMessage Get(long Id)
{
.....
将http方法属性添加到方法可能是多余的,因为我更改了方法名称以反映http方法,但此时我只是希望它能够工作。如果您有选项,请使用WebApi 2: - )