Проблема с GlobalConfiguration.Configure (WebApiConfig.Register) и зонтиком - PullRequest
0 голосов
/ 29 октября 2018

Привет У меня есть один проект Umbraco и 1 проект веб-API с использованием Umbraco. Я установил второй UmbracoCms.Core и у меня есть контроллер UmbracoAppiController

 public class TestController : UmbracoApiController
    {

        [HttpGet]
        public IEnumerable<string> GetAll()
        {
            return new string[] { "value1", "value2" };
        }
}

У меня есть global.asax.cs:

public class Global : System.Web.HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            RouteConfig.RegisterRoutes(RouteTable.Routes);            
        }
    }

и WebApiConfig.cs:

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

Когда я пытаюсь сделать веб-вызов API, я получаю:

Server Error in '/' Application.

Object reference not set to an instance of an object.  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error: 


Line 17:             // Code that runs on application startup Line 18: AreaRegistration.RegisterAllAreas(); Line 19:             GlobalConfiguration.Configure(WebApiConfig.Register); Line 20:         RouteConfig.RegisterRoutes(RouteTable.Routes);             Line 21:    }

Source File: C:\Projects\SBSADeviceShop5\ShopApi1\Global.asax.cs    Line: 19 

Stack Trace: 


[NullReferenceException: Object reference not set to an instance of an object.]    Umbraco.Web.WebApi.UnhandledExceptionLogger..ctor() +12    Umbraco.Web.WebApi.UnhandedExceptionLoggerConfigurationAttribute.Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor) +66 System.Web.Http.Controllers.HttpControllerDescriptor.InvokeAttributesOnControllerType(HttpControllerDescriptor controllerDescriptor, Type type) +188    System.Web.Http.Controllers.HttpControllerDescriptor.InvokeAttributesOnControllerType(HttpControllerDescriptor controllerDescriptor, Type type) +62    System.Web.Http.Controllers.HttpControllerDescriptor..ctor(HttpConfiguration configuration, String controllerName, Type controllerType) +130    System.Web.Http.Dispatcher.DefaultHttpControllerSelector.InitializeControllerInfoCache()
+568    System.Lazy`1.CreateValue() +708    System.Lazy`1.LazyInitValue() +184    System.Web.Http.Dispatcher.DefaultHttpControllerSelector.GetControllerMapping()
+18    System.Web.Http.Routing.AttributeRoutingMapper.AddRouteEntries(SubRouteCollection collector, HttpConfiguration configuration, IInlineConstraintResolver constraintResolver, IDirectRouteProvider directRouteProvider) +76    System.Web.Http.Routing.<>c__DisplayClass1_1.<MapAttributeRoutes>b__1()
+75    System.Web.Http.Routing.RouteCollectionRoute.EnsureInitialized(Func`1 initializer) +66    System.Web.Http.Routing.<>c__DisplayClass1_0.<MapAttributeRoutes>b__0(HttpConfiguration config) +125    ShopApi1.Global.Application_Start(Object sender, EventArgs e) in C:\Projects\SBSADeviceShop5\ShopApi1\Global.asax.cs:19

[HttpException (0x80004005): Object reference not set to an instance of an object.]    System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +520    System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +176    System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +165    System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +267    System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +341

[HttpException (0x80004005): Object reference not set to an instance of an object.]    System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +523    System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context)
+107    System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +688


Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.3160.0

Пожалуйста, помогите

1 Ответ

0 голосов
/ 29 октября 2018

Вам вообще не нужно делать файлы Global.asax.cs или WebApiConfig.cs - Umbraco автоматически выполняет маршрутизацию, если вы наследуете от UmbracoApiController или SurfaceController.

Прочтите документацию по маршрутизации на our.umbraco.com, в частности, раздел о WebApi:

https://our.umbraco.com/documentation/Reference/Routing/WebApi

Исходя из этого, ваш маршрут для вашего TestController будет выглядеть примерно так:

~/Umbraco/Api/Test/GetAll
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...