我一直在努力进行基于属性路由的WebApi2设置,但我已经没有想法可能会出现什么问题。以下代码是Visual Studio 2015新创建的WebApi项目。它没有任何变化。它根本不起作用。
回复说明如下:
<Error>
<Message>
No HTTP resource was found that matches the request URI 'http://.../services/webapi2/api/dummies/dummymethod'.
</Message>
<MessageDetail>
No type was found that matches the controller named 'dummies'.
</MessageDetail>
</Error>
到目前为止我做了什么:
提前感谢您的帮助!
DummyController.cs
using System.Web.Http;
namespace WebApi2.Controllers
{
[RoutePrefix( "Dummies" )]
public class Dummy : ApiController
{
[Route("dummymethod")]
public string Get()
{
return "asdasd";
}
}
}
WebApiConfig.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace WebApi2
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
已安装的软件包:
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.AspNet.WebApi" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="1.0.0" targetFramework="net452" />
<package id="Microsoft.Net.Compilers" version="1.0.0" targetFramework="net452" developmentDependency="true" />
<package id="Newtonsoft.Json" version="6.0.4" targetFramework="net452" />
</packages>
答案 0 :(得分:4)
您使用的路由前缀仅为dummies
的属性路由,因此它将映射到此网址
http://.../services/webapi2/dummies/dummymethod
请使用上述网址或更新路线前缀以包含api
以匹配示例中使用的网址
namespace WebApi2.Controllers
{
[RoutePrefix( "api/Dummies" )]
public class Dummy : ApiController
{
//GET api/dummies/dummymethod
[HttpGet]
[Route("dummymethod")]
public string Get()
{
return "asdasd";
}
}
}
以上内容与请求URI http://.../services/webapi2/api/dummies/dummymethod