我有一个ASP.net Web Api项目,决定支持版本控制。我使用微软官方Nuget来支持版本控制(更多信息请参见 这里),并且我决定按命名空间进行版本控制(例如 这里)。
不幸的是,我无法让代码正常工作。如果我像这样调用我的方法:
我遇到了一个错误:
如果我这样调用它:
不幸的是,我无法让代码正常工作。如果我像这样调用我的方法:
http://localhost:7291/api/Saved/GetNumberOfSavedWorkoutsForUser?api-version=2.0
我遇到了一个错误:
Multiple types were found that match the controller named 'Saved'. This can happen if the route that services this request ('api/{controller}/{action}/{id}') found multiple controllers defined with the same name but differing namespaces, which is not supported.
如果我这样调用它:
http://localhost:7291/v2/Saved/GetNumberOfSavedWorkoutsForUser
,会出现404错误。该接口与用户保存的锻炼计划相关。The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
我不确定我做错了什么。这是我的代码:
Startup.cs
public void Configuration(IAppBuilder app)
{
var configuration = new HttpConfiguration();
var httpServer = new HttpServer(configuration);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
// reporting api versions will return the headers "api-supported-versions" and "api-deprecated-versions"
configuration.AddApiVersioning(o =>
{
o.AssumeDefaultVersionWhenUnspecified = true;
o.ReportApiVersions = true;
o.DefaultApiVersion = ApiVersion.Default;
});
configuration.Routes.MapHttpRoute(
"VersionedUrl",
"v{apiVersion}/{controller}/{action}/{id}",
defaults: null,
constraints: new { apiVersion = new ApiVersionRouteConstraint() });
configuration.Routes.MapHttpRoute(
"VersionedQueryString",
"api/{controller}/{action}/{id}",
defaults: null);
app.UseWebApi(httpServer);
ConfigureAuth(app);
}
保存的控制器(v1)
namespace Master.Infrastructure.Api.Controllers
{
[Authorize]
[RoutePrefix("api/Saved")]
[ApiVersion("1.0")]
public class SavedController : ApiController
{
private readonly IUserService _userService;
public SavedController(IUserService userService)
{
_userService = userService;
}
[HttpGet]
[ActionName("GetNumberOfSavedWorkouts")]
public async Task<NumberOfSavedWorkouts> GetNumberOfSavedWorkouts()
{
var numOfSavedWorkouts = new NumberOfSavedWorkouts
{
CurrentNumberOfSavedWorkouts =
await _userService.GetNumberOfSavedWorkoutsForUserAsync(User.Identity.GetUserId())
};
return numOfSavedWorkouts;
}
}
}
Saved Controller (v2)
namespace Master.Infrastructure.Api.V2.Controllers
{
[Authorize]
[ApiVersion("2.0")]
[RoutePrefix("v{version:apiVersion}/Saved")]
public class SavedController : ApiController
{
private readonly ISavedWorkoutService _savedWorkoutService;
public SavedController(ISavedWorkoutService savedWorkoutService)
{
_savedWorkoutService = savedWorkoutService;
}
[ActionName("GetNumberOfSavedWorkoutsForUser")]
public async Task<IHttpActionResult> GetNumberOfSavedWorkoutsForUser()
{
var cnt = await _savedWorkoutService.CountNumberOfSavedWorkoutsForUser(User.Identity.GetUserId());
return Ok(cnt);
}
}
}
configuration.MapHttpAttributeRoutes()
。 - Chris Martinez