У меня есть проект C# с использованием Web API. Я определил мой префикс и маршрутизации для моего контроллера, но я постоянно получаю сообщение об ошибке при попытке получить доступ к «все» по маршруту:Контроллер Web API не распознан
{
"message": "No HTTP resource was found that matches the request URI '.../api/InventoryOnHand/all'.",
"messageDetail": "No type was found that matches the controller named 'InventoryOnHand'."
}
Вот мой контроллер:
[RoutePrefix("api/inventoryonhand")]
public class InventoryOnHandController : ApiController
{
public InventoryOnHandController(){}
[HttpGet]
[Route("all")]
[CacheOutput(ClientTimeSpan = 50, MustRevalidate = true)]
public IHttpActionResult GetAllInventoryOnHand()
{
// Do stuff
}
}
Мой WebApiConfig ISN» (я думаю), потому что у нас есть другие маршруты, которые работают отлично, не могу понять, почему этот человек странный. Наша маршрутизация в WebApiConfig:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
EDIT Добавление файла WebApiConfig:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// require authenticated users in all controllers/action unless decoratd with "[AllowAnonymous]"
config.Filters.Add(new AuthorizeAttribute());
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
config.Services.Add(typeof(IExceptionLogger), new SerilogExceptionLogger());
ConfigureJsonHandling(config.Formatters.JsonFormatter);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Web API routes
config.MapHttpAttributeRoutes();
}
private static void ConfigureJsonHandling(JsonMediaTypeFormatter json)
{
//make our json camelCase and not include NULL or default values
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
json.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore;
json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
}
EDIT Добавление файла запуска (укороченный для краткости):
public void Configuration(IAppBuilder app)
{
LoggingConfig.ConfigureLogger();
HttpConfiguration httpConfiguration = new HttpConfiguration();
var container = IoC.Initialize();
httpConfiguration.DependencyResolver = new StructureMapResolver(container);
ConfigAuth(app);
WebApiConfig.Register(httpConfiguration);
GlobalConfiguration.Configure(WebApiConfig.Register);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(httpConfiguration);
Log.Logger.ForContext<Startup>().Information("======= Starting Owin Application ======");
}
Вы проверили, является ли это проблемой чувствительности к регистру? – im1dermike
Просто попробовал варианты ** «inventoryonhandcontroller» ** и ** «inventoryonhandController» **, все еще не удалось. – Thomas
Убедитесь, что маршрут за частью «api» соответствует виртуальному каталогу в IIS. –