我正在尝试使用RoutePrefix,但ASP.NET部分忽略它。给定以下控制器(删除了方法体和类字段):
[RoutePrefix("api/users/sharepoint")]
public class SharePointController : ApiController
{
public SharePointController(ISharePointUserRepository repo, IAzureUserRepository otherRepo)
{
}
[HttpGet]
public ExternalUser Get(int id)
{
}
[HttpGet]
public ExternalUser Get(Guid guid)
{
}
[HttpGet]
public IEnumerable<ExternalUser> Get()
{
}
[HttpGet]
public ExternalUser Get(string username)
{
}
[HttpGet]
public IEnumerable<ExternalUser> GetByPersonalEmail(string email)
{
}
[HttpGet]
[Route("GetWithDifferences")]
public IEnumerable<ExternalUser> GetWithDifferences()
{
}
[HttpGet]
[Route("GetUnique")]
public IEnumerable<ExternalUser> GetUnique()
{
}
[HttpPost]
[Route("search")]
public IEnumerable<ExternalUser> Search([FromBody] ExternalUserSearchModel model)
{
}
我得到以下API(通过主机/帮助):
的SharePoint
获取api / users / sharepoint / GetWithDifferences
获取api / users / sharepoint / GetUnique
POST api / users / sharepoint / search
GET api / SharePoint / {id}
GET api / SharePoint?guid = {guid}
获取api / SharePoint
GET api / SharePoint?username = {username}
GET api / SharePoint?email = {email}
经过测试,其效果与宣传的一样。
正如您所看到的,当我没有为公开方法指定[Route(..)]时,将忽略RoutePrefix。但是我想要GET上的默认操作,所以我不想为这些操作指定任何其他路由。
如何强制执行RoutePrefix,或者如何使用[Route(..)]维护默认的GET和POST行为?
答案 0 :(得分:0)
RoutePrefixAttribute
没有定义任何路由,它只会将所选前缀添加到用这种属性修饰的类中定义的任何路径。
您需要做出选择:仅使用属性路由(并为每个方法定义路由),这样您可以从RoutePrefix
中受益,或保持代码不变,并定义另一个符合的路由路由你的URI。
使用属性路由的示例:
[HttpGet]
[Route("{id:int}"]
public ExternalUser Get(int id)
{ }
[HttpGet]
[Route(""]
public ExternalUser Get(Guid guid)
{ }
[HttpGet]
[Route("")]
public IEnumerable<ExternalUser> Get()
{ }
[HttpGet]
[Route("")]
public ExternalUser Get(string username)
{ }
这是第二种方法的另一个例子:
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "MyCustomApi",
routeTemplate: "api/users/sharepoint/{id}",
defaults: new { controller = "SharePoint", id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}