Ejemplo n.º 1
2
        public void Configuration(IAppBuilder appBuilder)
        {
            // Configure Web API for self-host.
            HttpConfiguration config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            appBuilder.UseWebApi(config);

            var appFolder = Path.Combine(Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).Parent.Parent.FullName, "Webportal");

            appBuilder.UseFileServer(new Microsoft.Owin.StaticFiles.FileServerOptions
            {
                RequestPath = new PathString(WebPortalUrl),
                FileSystem = new PhysicalFileSystem(appFolder),
                EnableDirectoryBrowsing = true

            });

            appBuilder.Map(PathString.Empty, a => a.Use<PortalRedirectionMiddelware>(WebPortalUrl));
            appBuilder.Use<AdminMiddleware>();
        }
Ejemplo n.º 2
2
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API routes
            config.MapHttpAttributeRoutes();

            // enable CORS
            config.EnableCors();

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

            config.Routes.MapHttpRoute(
                name: "PlayerApi",
                routeTemplate: "api/{controller}/{action}/{name}",
                defaults: new { teamName = RouteParameter.Optional }
            );
        }
Ejemplo n.º 3
1
        public void RegisterRoutes(HttpConfiguration config)
        {
            // blobs
            this.MapRoute(config, HttpMethod.Get , "api/file", "Blob", "Get");
            this.MapRoute(config, HttpMethod.Post, "api/file", "Blob", "Post");

            // nomenclatures
            this.MapRoute(config, HttpMethod.Get, "api/nomenclatures/{alias}/{id}"        , "Nom", "GetNom", new Dictionary<string, object>() { {"id", new IntRouteConstraint() } });
            this.MapRoute(config, HttpMethod.Get, "api/nomenclatures/{alias}/{valueAlias}", "Nom", "GetNom");
            this.MapRoute(config, HttpMethod.Get, "api/nomenclatures/{alias}"             , "Nom", "GetNoms");

            // signs
            this.MapRoute(config, HttpMethod.Post, "api/signXml", "Sign", "PostSignXml");
            this.MapRoute(config, HttpMethod.Post, "api/signOffice", "Sign", "PostSignOffice");

            //user
            this.MapRoute(config, HttpMethod.Get, "api/user/currentData", "User", "GetUserData");
            this.MapRoute(config, HttpMethod.Get, "api/user/duplicateUnit", "User", "CheckDuplicateUnit");
            this.MapRoute(config, HttpMethod.Get, "api/users", "User", "GetUsers");
            this.MapRoute(config, HttpMethod.Get, "api/users/{id}", "User", "GetUser");
            this.MapRoute(config, HttpMethod.Post, "api/users/{id}", "User", "UpdateUser");
            this.MapRoute(config, HttpMethod.Post, "api/users", "User", "CreateUser");

            this.MapRoute(config, HttpMethod.Post, "api/user/changePassword", "User", "ChangeCurrentUserPassword");
            this.MapRoute(config, HttpMethod.Post, "api/user/isCorrectPassword", "User", "IsCorrectPassword");

            //role
            this.MapRoute(config, HttpMethod.Get, "api/roles", "User", "GetRoles");
        }
Ejemplo n.º 4
1
        public static void Register(HttpConfiguration config)
        {
            //// Uncomment the following to use the documentation from XML documentation file.
            //config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));

            //// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type.
            //// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type 
            //// formats by the available formatters.
            //config.SetSampleObjects(new Dictionary<Type, object>
            //{
            //    {typeof(string), "sample string"},
            //    {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}}
            //});

            //// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format
            //// and have IEnumerable<string> as the body parameter or return type.
            //config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>));

            //// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values"
            //// and action named "Put".
            //config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put");

            //// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png"
            //// on the controller named "Values" and action named "Get" with parameter "id".
            //config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id");

            //// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>.
            //// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter.
            //config.SetActualRequestType(typeof(string), "Values", "Get");

            //// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>.
            //// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string.
            //config.SetActualResponseType(typeof(string), "Values", "Post");
        }
Ejemplo n.º 5
1
        public static void Configure(HttpConfiguration config)
        {
            // Message Handlers
            config.MessageHandlers.Add(new RequireHttpsMessageHandler());
            config.MessageHandlers.Add(new PingYourPackageAuthHandler());

            //Formatters
            var jqueryFormatter = config.Formatters.FirstOrDefault(
            x => x.GetType() ==
            typeof(JQueryMvcFormUrlEncodedFormatter));
            config.Formatters.Remove(
            config.Formatters.FormUrlEncodedFormatter);

            config.Formatters.Remove(jqueryFormatter);

            foreach (var formatter in config.Formatters)
            {
                formatter.RequiredMemberSelector =
                new SuppressedRequiredMemberSelector();
            }

            // Filters
            config.Filters.Add(
            new InvalidModelStateFilterAttribute());

            //Default Services
            config.Services.Replace(typeof(IContentNegotiator), new DefaultContentNegotiator(
            excludeMatchOnTypeOnly: true));
            config.Services.RemoveAll(typeof(ModelValidatorProvider), validator => !(validator
            is DataAnnotationsModelValidatorProvider));

            // ParameterBindingRules
            config.ParameterBindingRules.Insert(0,descriptor => typeof(IRequestCommand).IsAssignableFrom(descriptor.ParameterType)? new FromUriAttribute().GetBinding(descriptor) : null);
        }
Ejemplo n.º 6
1
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            var cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);

            // Web API routes
            config.MapHttpAttributeRoutes();

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

            //clear default formatters 
            config.Formatters.Clear();
            config.Formatters.Add(new JsonMediaTypeFormatter());

            //set formatters only json 
            var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
            //optional: set serializer settings here
            config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
                        
            //jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }
Ejemplo n.º 7
1
        public static void RegisterWebApiRoutes(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "AccountApi",
                routeTemplate: "api/account/{action}/{id}",
                defaults: new { controller = "Account",  id = RouteParameter.Optional }
            );

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

            config.Routes.MapHttpRoute(
                name: "BreezeDefault",
                routeTemplate: "breeze/{action}",
                defaults: new { Controller = "Metadata" }
            );

            config.Routes.MapHttpRoute(
                name: "BreezeModule",
                routeTemplate: "breeze/{controller}/{action}"
            );

            config.EnableQuerySupport();
        }
        [InlineData("GET", "http://localhost/Customers(12)/NS.SpecialCustomer/NS.GetSalary()", "GetSalaryFromSpecialCustomer_12")] // call function on derived entity type
        public async Task AttriubteRouting_SelectsExpectedControllerAndAction(string method, string requestUri,
            string expectedResult)
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();

            var controllers = new[] { typeof(CustomersController), typeof(MetadataAndServiceController), typeof(OrdersController) };
            TestAssemblyResolver resolver = new TestAssemblyResolver(new MockAssembly(controllers));

            HttpConfiguration config = new HttpConfiguration();
            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            config.Services.Replace(typeof(IAssembliesResolver), resolver);

            config.MapODataServiceRoute("odata", "", model.Model);

            HttpServer server = new HttpServer(config);
            config.EnsureInitialized();

            HttpClient client = new HttpClient(server);
            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(method), requestUri);

            // Act
            var response = await client.SendAsync(request);

            // Assert
            if (!response.IsSuccessStatusCode)
            {
                Assert.False(true, await response.Content.ReadAsStringAsync());
            }
            var result = await response.Content.ReadAsAsync<AttributeRoutingTestODataResponse>();
            Assert.Equal(expectedResult, result.Value);
        }
Ejemplo n.º 9
1
 public static void Register(HttpConfiguration config) {
     config.Routes.MapHttpRoute(
         name: "DefaultApi",
         routeTemplate: "api/{controller}/{id}",
         defaults: new {id = RouteParameter.Optional}
         );
 }
Ejemplo n.º 10
1
 private static void setJsonSettings(HttpConfiguration config)
 {
     config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
     config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
     config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new DateTimeConverter());
     config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
 }
Ejemplo n.º 11
1
        public static void Register(HttpConfiguration config)
        {
            //config.Formatters.JsonFormatter.("json", "application/json");
            //config.Formatters.XmlFormatter.AddUriPathExtensionMapping("xml", "text/xml");
            // TODO: read format based on extension
            config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
            config.Formatters.JsonFormatter.MediaTypeMappings.Add(
                new UriPathExtensionMapping("json", "application/json"));

            config.Routes.MapHttpRoute(
                name: "ActivityApi",
                routeTemplate: "{appName}/activity/{subjectId}/{actionName}/{objectId}",
                defaults: new { Controller = "ActivityApi", objectId = RouteParameter.Optional } //, ext = RouteParameter.Optional }
            );

            config.Routes.MapHttpRoute(
                name: "RulesApi",
                routeTemplate: "{appName}/rules/{id}",
                defaults: new { Controller = "RulesApi", id = RouteParameter.Optional } //, ext = RouteParameter.Optional }
            );

            config.Routes.MapHttpRoute(
                name: "ReputationApi",
                routeTemplate: "{appName}/{objectId}/reputation/{stat}",
                defaults: new { Controller = "ReputationApi", stat = RouteParameter.Optional } //, ext = RouteParameter.Optional }
            );

            config.Routes.MapHttpRoute(
                name: "ReputationApiGlobal",
                routeTemplate: "{objectId}/reputation/{stat}",
                defaults: new { Controller = "ReputationApi", stat = RouteParameter.Optional } //, ext = RouteParameter.Optional }
            );
        }
Ejemplo n.º 12
1
        public static RouteInfo RouteRequest(HttpConfiguration config, HttpRequestMessage request)
        {
            // create context
            var controllerContext = new HttpControllerContext(config, Substitute.For<IHttpRouteData>(), request);

            // get route data
            var routeData = config.Routes.GetRouteData(request);
            RemoveOptionalRoutingParameters(routeData.Values);

            request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;
            controllerContext.RouteData = routeData;

            // get controller type
            var controllerDescriptor = new DefaultHttpControllerSelector(config).SelectController(request);
            controllerContext.ControllerDescriptor = controllerDescriptor;

            // get action name
            var actionMapping = new ApiControllerActionSelector().SelectAction(controllerContext);

            return new RouteInfo
            {
                Controller = controllerDescriptor.ControllerType,
                Action = actionMapping.ActionName
            };
        }
Ejemplo n.º 13
1
        public Generator(HttpConfiguration conf, HttpRequestMessage req)
        {
            config = conf;
            request = req;

            GenerateRouteData();
        }
Ejemplo n.º 14
1
 public static void Register(HttpConfiguration configuration)
 {
     container = new WindsorContainer();
     container.Install(FromAssembly.This());
     container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel, true));
     configuration.Services.Replace(typeof (IHttpControllerActivator), new WindsorCompositionRoot(container));
 }
Ejemplo n.º 15
1
        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 }
            //);

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

            GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));
            GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));

            // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
            // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
            // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
            //config.EnableQuerySupport();

            // To disable tracing in your application, please comment out or remove the following line of code
            // For more information, refer to: http://www.asp.net/web-api
            //config.EnableSystemDiagnosticsTracing();
        }
Ejemplo n.º 16
1
        // This code configures Web API. The Startup class is specified as a type
        // parameter in the WebApp.Start method.
        public void Configuration(IAppBuilder appBuilder)
        {

            // Configure Web API for self-host. 
            HttpConfiguration config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            // 默认返回Json数据
            //config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

            //var bson = new BsonMediaTypeFormatter();
            //bson.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/bson"));
            //config.Formatters.Add(bson);
            config.Formatters.Add(new Raven.AspNet.WebApiExtensions.Formatters.MsgPackFormatter());

            appBuilder.UseRequestScopeContext();
            appBuilder.UseWebApi(config);
            
            //CallContext
            //appBuilder.Use(
        }
        public void ByPostShouldReturnCorrectResponse()
        {
            var controller = typeof(CategoriesController);

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

            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            var httpServer = new HttpServer(config);
            var httpInvoker = new HttpMessageInvoker(httpServer);

            using (httpInvoker)
            {
                var request = new HttpRequestMessage
                {
                    RequestUri = new Uri("http://test.com/api/categories/1"),
                    Method = HttpMethod.Get
                };

                var result = httpInvoker.SendAsync(request, CancellationToken.None).Result;

                Assert.IsNotNull(result);
            }
        }
Ejemplo n.º 18
1
        public static void Register(HttpConfiguration config)
        {
            config.EnableCors();

            // Web API configuration and services
            var clientID = WebConfigurationManager.AppSettings["auth0:ClientId"];
            var clientSecret = WebConfigurationManager.AppSettings["auth0:ClientSecret"];

            config.MessageHandlers.Add(new JsonWebTokenValidationHandler()
            {
                Audience = clientID,
                SymmetricKey = clientSecret
            });

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "WithActionApi",
                routeTemplate: "api/{controller}/{action}/{fillupId}"
            );

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
Ejemplo n.º 19
1
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            // 取消注释下面的代码行可对具有 IQueryable 或 IQueryable<T> 返回类型的操作启用查询支持。
            // 若要避免处理意外查询或恶意查询,请使用 QueryableAttribute 上的验证设置来验证传入查询。
            // 有关详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=279712。
            //config.EnableQuerySupport();

            // 若要在应用程序中禁用跟踪,请注释掉或删除以下代码行
            // 有关详细信息,请参阅: http://www.asp.net/web-api
            config.EnableSystemDiagnosticsTracing();

            // 参考:http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/odata-v3/creating-an-odata-endpoint
            var builder = new ODataConventionModelBuilder();
            builder.EntitySet<Product>("Products");
            // 参考:http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/odata-v3/working-with-entity-relations
            builder.EntitySet<Supplier>("Suppliers");
            //config.Routes.MapODataRoute("OData", "odata", builder.GetEdmModel());
            config.Routes.MapODataServiceRoute("ODataRoute", "odata", builder.GetEdmModel());
        }
Ejemplo n.º 20
1
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();
        }
Ejemplo n.º 21
1
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            //Unity
            var container = new UnityContainer();
            container.RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager());
            container.RegisterType<IGenericRepository<Farmacia>, GenericRepository<Farmacia>>(new HierarchicalLifetimeManager());
            config.DependencyResolver = new UnityResolver(container);

            //Formatters
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
            //GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
            //config.Formatters.Insert(0, new System.Net.Http.Formatting.JsonMediaTypeFormatter());

            // Web API routes
            config.MapHttpAttributeRoutes();
            //config.EnableCors();
            var cors = new EnableCorsAttribute("http://localhost:28285", "*", "*");
            config.EnableCors(cors);

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
Ejemplo n.º 22
1
 public void Configuration(IAppBuilder appBuilder)
 {
     var config = new HttpConfiguration();
     config.MapHttpAttributeRoutes();
     config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new {id = RouteParameter.Optional});
     appBuilder.UseWebApi(config).UseNancy();
 }
Ejemplo n.º 23
0
        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 }
            );

            // Load basic support for sending WebHooks
            config.InitializeCustomWebHooks();

            // Load Azure Storage or SQL for persisting subscriptions
            config.InitializeCustomWebHooksAzureStorage();
            // config.InitializeCustomWebHooksSqlStorage();

            // Load Azure Queued Sender for enqueueing outgoing WebHooks to an Azure Storage Queue
            // config.InitializeCustomWebHooksAzureQueueSender();

            // Load Web API controllers for managing subscriptions
            config.InitializeCustomWebHooksApis();
        }
        public static new void Install(HttpConfiguration config, IAppBuilder app)
        {
            config.SuppressHostPrincipal();

            app.UseCors(CorsOptions.AllowAll);

            app.MapSignalR();

            var jSettings = new JsonSerializerSettings();

            jSettings.Formatting = Formatting.Indented;

            jSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            config.Formatters.Remove(config.Formatters.XmlFormatter);

            config.Formatters.JsonFormatter.SerializerSettings = jSettings;

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
        }
        public AuthorizationLevelAttributeTests()
        {
            HttpConfig     = new System.Web.Http.HttpConfiguration();
            _actionContext = CreateActionContext(typeof(TestController).GetMethod("Get"), HttpConfig);

            Mock <IDependencyResolver> mockDependencyResolver = new Mock <IDependencyResolver>(MockBehavior.Strict);

            HttpConfig.DependencyResolver = mockDependencyResolver.Object;
            MockSecretManager             = new Mock <ISecretManager>(MockBehavior.Strict);
            _hostSecrets = new HostSecretsInfo
            {
                MasterKey    = TestMasterKeyValue,
                FunctionKeys = new Dictionary <string, string>
                {
                    { TestHostFunctionKeyName1, TestHostFunctionKeyValue1 },
                    { TestHostFunctionKeyName2, TestHostFunctionKeyValue2 }
                },
                SystemKeys = new Dictionary <string, string>
                {
                    { TestSystemKeyName1, TestSystemKeyValue1 },
                    { TestSystemKeyName2, TestSystemKeyValue2 }
                }
            };
            MockSecretManager.Setup(p => p.GetHostSecretsAsync()).ReturnsAsync(_hostSecrets);
            _functionSecrets = new Dictionary <string, string>
            {
                { TestFunctionKeyName1, TestFunctionKeyValue1 },
                { TestFunctionKeyName2, TestFunctionKeyValue2 }
            };
            MockSecretManager.Setup(p => p.GetFunctionSecretsAsync(It.IsAny <string>(), false)).ReturnsAsync(_functionSecrets);
            mockDependencyResolver.Setup(p => p.GetService(typeof(ISecretManager))).Returns(MockSecretManager.Object);
            _webHostSettings = new WebHostSettings();
            mockDependencyResolver.Setup(p => p.GetService(typeof(WebHostSettings))).Returns(_webHostSettings);
        }
Ejemplo n.º 26
0
        public void Configuration(IAppBuilder app)
        {
            var startupType  = typeof(IStartup);
            var assemblies   = AppDomain.CurrentDomain.GetAssemblies();
            var startupTypes = assemblies.SelectMany(s => GetAssemblyTypes(s, startupType));

            var startupInstances = new List <IStartup>();

            foreach (var sType in startupTypes)
            {
                var startupInstance = Activator.CreateInstance(sType) as IStartup;
                startupInstances.Add(startupInstance);
            }

            // Register HttpConfiguration
            var config = new System.Web.Http.HttpConfiguration();

            config.MapHttpAttributeRoutes();

            foreach (var sType in startupInstances)
            {
                sType.Register(config, app);
            }

            // Set up all configuration.
            foreach (var sType in startupInstances)
            {
                sType.Configuration(app);
            }

            app.UseWebApi(config);
        }
Ejemplo n.º 27
0
        public static void Register(HttpConfiguration httpConfiguration)
        {
            ODataModelBuilder builder = new ODataConventionModelBuilder();
            builder.Namespace = "ODataV4TestService.Models";
            builder.EntitySet<Product>("Products");
            builder.EntitySet<SuppliedProduct>("SuppliedProducts");
            builder.EntitySet<Supplier>("Suppliers");
            builder.EntitySet<Product>("OtherProducts");

            builder.ComplexType<Description>();
            builder.EntityType<Product>()
                .Action("Rate")
                .Parameter<int>("Rating");

            builder.EntityType<Product>().Collection
                .Function("Best")
                .ReturnsCollectionFromEntitySet<Product>("Products");

            var funcConfig = builder
                .EntityType<Product>()
                .Function("RelatedProducts")
                .SetBindingParameter("product", builder.GetTypeConfigurationOrNull(typeof(Product)))
                //.AddParameter("start", new PrimitiveTypeConfiguration(builder, builder.GetTypeConfigurationOrNull(typeof(DateTimeOffset)), typeof(DateTimeOffset)).
                .ReturnsCollectionFromEntitySet<Product>("Products");

            funcConfig
                .Parameter<DateTimeOffset>("start");

            funcConfig
                .Parameter<DateTimeOffset>("end");

            //builder.Function("GetSalesTaxRate")
            //    .Returns<double>()
            //    .Parameter<int>("PostalCode");

            builder.EntitySet<Account>("Accounts");

            builder.EntityType<PaymentInstrument>()
                .Collection
                .Function("GetCount")
                .Returns<int>()
                .Parameter<string>("NameContains");

            var model = builder.GetEdmModel();

            var conventions = ODataRoutingConventions.CreateDefault();
            conventions.Insert(0, new AttributeRoutingConvention(model, httpConfiguration));

            var server = new BatchServer(httpConfiguration);

            httpConfiguration.MapODataServiceRoute(
                routeName: "ODataRoute",
                routePrefix: null,
                model: model,
                pathHandler: new DefaultODataPathHandler(),
                routingConventions: conventions,
                batchHandler: new DefaultODataBatchHandler(server));

            httpConfiguration.MessageHandlers.Add(new TracingMessageHandler());
        }
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "ThreadsApi",
                routeTemplate: "api/threads/{threadId}/posts",
                defaults: new 
                { 
                    controller = "threads",
                    action = "posts"
                }
            );

            config.Routes.MapHttpRoute(
                name: "UsersApi",
                routeTemplate: "api/users/{action}",
                defaults: new { controller = "users" }
            );

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

            // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
            // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
            // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
            //config.EnableQuerySupport();

            // To disable tracing in your application, please comment out or remove the following line of code
            // For more information, refer to: http://www.asp.net/web-api
            config.EnableSystemDiagnosticsTracing();
        }
Ejemplo n.º 29
0
        public void Configuration(IAppBuilder app)
        {
            var cookieOptions = new CookieAuthenticationOptions()
            {
                LoginPath          = new PathString("/LoginHandler"),
                AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
                Provider           = new AppCookieAuthProvider()
            };

            app.UseCookieAuthentication(cookieOptions);

            // web api
            var apiConfig = new System.Web.Http.HttpConfiguration();

            //apiConfig.MapHttpAttributeRoutes();
            //apiConfig.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
            apiConfig.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );


            app.UseWebApi(apiConfig);

            //app.Run(context =>
            //{
            //    context.Response.ContentType = "plain/html";
            //    return context.Response.WriteAsync("Hello World!");
            //});
        }
Ejemplo n.º 30
0
        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 }
            );

            // OData
            ODataModelBuilder builder = new ODataConventionModelBuilder();
            builder.EntitySet<Player>("Players");
            builder.EntitySet<BattingDetail>("BattingDetails");
            builder.EntitySet<BowlingDetail>("BowlingDetails");
            builder.EntitySet<Country>("Countrys");
            builder.EntitySet<Match>("Matches").EntityType.HasKey(m => m.MatchNumber);
            config.AddODataQueryFilter();
            config.MapODataServiceRoute(
                routeName: "odata",
                routePrefix: "odata",
                model: builder.GetEdmModel());
        }
Ejemplo n.º 31
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            //2014/06/16 若以此設定在get/put的方法會造成404,因為參數api/products/1的products對到了area,1對到了controller,id=optional
            //            config.Routes.MapHttpRoute(
            //name: "AreaAPI",
            //routeTemplate: "api/{area}/{controller}/{id}",
            //defaults: new { id = RouteParameter.Optional }
            //                //, constraints: new { area = @"\w{3}|\w{4}|\w{5}|\w{6}|\w{7}" }//限定Area才吃此設定,防put 404 error,   2014/06/16無效
            //);

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

            //2014/08/11重點為default的id約束及DefaultApiWithAction,可以使用明確的action來呼叫
            //2014/08/11看起來WebApi最好的設定方式
            //http://lonetechie.com/2013/03/04/fixing-multiple-actions-were-found-that-match-the-request-aspnet-webapi/
            config.Routes.MapHttpRoute("DefaultApiWithId", "api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
            config.Routes.MapHttpRoute("DefaultApiWithAction", "api/{controller}/{action}");
            config.Routes.MapHttpRoute("DefaultApiGet", "api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });
            config.Routes.MapHttpRoute("DefaultApiPost", "api/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) });
            config.Routes.MapHttpRoute("DefaultApiPut", "api/{controller}", new { action = "Put" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Put) });
            config.Routes.MapHttpRoute("DefaultApiDelete", "api/{controller}", new { action = "Delete" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Delete) });
        }
Ejemplo n.º 32
0
        public void Configuration(IAppBuilder app)
        {
            var httpConfiguration = new HttpConfiguration();

            // Configure Web API Routes:
            // - Enable Attribute Mapping
            // - Enable Default routes at /api.
            httpConfiguration.MapHttpAttributeRoutes();
            httpConfiguration.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            app.UseWebApi(httpConfiguration);

            // Make ./public the default root of the static files in our Web Application.
            app.UseFileServer(new FileServerOptions
            {
                RequestPath = new PathString(string.Empty),
                FileSystem = new PhysicalFileSystem("./public"),
                EnableDirectoryBrowsing = true,
            });

            app.UseStageMarker(PipelineStage.MapHandler);
        }
Ejemplo n.º 33
0
 public void Configuration(IAppBuilder app)
 {
     var config = new HttpConfiguration();
     ConfigureOAuth(app);
     WebApiConfig.Register(config);
     app.UseWebApi(config);
 }
        private static HttpConfiguration GetNewHttpConfig()
        {
            HttpConfiguration config = new System.Web.Http.HttpConfiguration();

            config.EnableDependencyInjection(); //1
            config.EnsureInitialized();         //2
            return(config);
        }
Ejemplo n.º 35
0
 public static void Register(System.Web.Http.HttpConfiguration config)
 {
     config.Routes.MapHttpRoute(
         name: "DefaultApi",
         routeTemplate: "api/{controller}/{id}",
         defaults: new { id = RouteParameter.Optional }
         );
 }
Ejemplo n.º 36
0
        public static void Register(System.Web.Http.HttpConfiguration config)
        {
            var container = new ServiceContainer();

            Container = container;
            container.RegisterApiControllers(typeof(IocConfig).Assembly);
            container.EnableWebApi(config);
            RegisterServices(container);
        }
Ejemplo n.º 37
0
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     new Logging.LogManager();
     System.Web.Http.HttpConfiguration conf = new System.Web.Http.HttpConfiguration();
     conf.EnableSystemDiagnosticsTracing();
 }
Ejemplo n.º 38
0
        public void Configuration(IAppBuilder app)
        {
            System.Web.Http.HttpConfiguration config = new System.Web.Http.HttpConfiguration();
            config.Routes.MapHttpRoute("r1", "{controller}/{action}/{id}/", defaults: new { id = RouteParameter.Optional });
            config.Filters.Add(new AzFilter());

            app.UseWebApi(config);

            // 有关如何配置应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=316888
        }
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     GlobalConfiguration.Configure(WebApiConfig.Register);
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     UnityConfig.RegisterComponents();
     System.Web.Http.HttpConfiguration config = System.Web.Http.GlobalConfiguration.Configuration;
     config.EnsureInitialized();
 }
        public ExceptionProcessingHandler(System.Web.Http.HttpConfiguration config)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            _config            = config;
            _traceWriterLoader = new Lazy <TraceWriter>(() => _config.DependencyResolver.GetService <TraceWriter>());
            _handlers          = InitializeExceptionHandlers();
        }
        public async Task <ActionResult> Index(Models.SendNotificationsModel model)
        {
            //get notification hub information
            // Get the settings for the server project.

            System.Web.Http.HttpConfiguration config =
                System.Web.Http.GlobalConfiguration.Configuration;
            MobileAppSettingsDictionary settings =
                config.GetMobileAppSettingsProvider().GetMobileAppSettings();

            // Get the Notification Hubs credentials for the Mobile App.
            string notificationHubName       = settings.NotificationHubName;
            string notificationHubConnection = settings
                                               .Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;

            // Create a new Notification Hub client.
            NotificationHubClient hub = NotificationHubClient
                                        .CreateClientFromConnectionString(notificationHubConnection, notificationHubName);

            // Sending the message so that all template registrations that contain "messageParam"
            // will receive the notifications. This includes APNS, GCM, WNS, and MPNS template registrations.
            Dictionary <string, string> templateParams = new Dictionary <string, string>();

            templateParams["title"]   = model.Title;
            templateParams["message"] = model.Message;

            try
            {
                NotificationOutcome result = null;

                // Send the push notification and log the results.
                if (model.Tags != null && model.Tags.Count > 0)
                {
                    result = await hub.SendTemplateNotificationAsync(templateParams, String.Join(" || ", model.Tags));
                }
                else
                {
                    result = await hub.SendTemplateNotificationAsync(templateParams);
                }

                // Write the success result to the logs.
                config.Services.GetTraceWriter().Info(result.State.ToString());
            }
            catch (System.Exception ex)
            {
                // Write the failure result to the logs.
                config.Services.GetTraceWriter()
                .Error(ex.Message, null, "Push.SendAsync Error");
                throw;
            }

            //redirct to confirm
            return(View("Confirm"));
        }
Ejemplo n.º 42
0
        public WebViewer(ILogger logger, Action <Action <ISystemController, IRaceController> > queueCommand, IPlugin plugin, IKernel kernel)
        {
            //params to add:
            //wifi hostspot?
            //dhcp?
            //dns?

            //katana port
            //static content path


            _logger     = logger;
            this.Plugin = plugin;

            //possibly do these as another plugin/dependency eg how bt or i2c works?
            //optionally configure wifi as hotspot
            //optionally configure dhcp
            //optionally configure dns

            //initialize owin/katana
            _webApp = WebApp.Start("http://*:9000", app =>
            {
                var webApiConfig = new System.Web.Http.HttpConfiguration();
                webApiConfig.MapHttpAttributeRoutes();
                webApiConfig.Formatters.Clear();
                webApiConfig.Formatters.Add(new JsonMediaTypeFormatter());
                webApiConfig.Formatters.JsonFormatter.SerializerSettings =
                    new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                };

                _resolver = new WebResolver(webApiConfig.DependencyResolver, logger, queueCommand, kernel);
                webApiConfig.DependencyResolver = _resolver;
                app.UseWebApi(webApiConfig);

                var fs = new PhysicalFileSystem("/home/brook/Desktop/MrGibbs/src/MrGibbs.OnboardWebUI/Web");
                app.UseFileServer(new FileServerOptions()
                {
                    FileSystem         = fs,
                    RequestPath        = new PathString(""),
                    EnableDefaultFiles = true
                });
            });
            //initialize static content
            //initialize default page
            //initialize webapi

            //initialize websockets/signalr?

            //create a ninject kernel specifically for the webapp
            //add the logger and queue command, maybe state?
        }
Ejemplo n.º 43
0
        public ExceptionProcessingHandlerTests()
        {
            _settingsManager = ScriptSettingsManager.Instance;
            _traceWriter     = new TestTraceWriter(System.Diagnostics.TraceLevel.Verbose);

            Mock <IDependencyResolver> mockResolver = new Mock <IDependencyResolver>();

            mockResolver.Setup(p => p.GetService(typeof(TraceWriter))).Returns(_traceWriter);

            _config = new System.Web.Http.HttpConfiguration();
            _config.DependencyResolver = mockResolver.Object;
        }
Ejemplo n.º 44
0
        public static void RegisterApi(System.Web.Http.HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

            // Adds support for the webapi 1 style methods, e.g. /api/Users/
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            config.EnsureInitialized();
        }
        public static void Register(System.Web.Http.HttpConfiguration config)
        {
            var authConfig = new AuthenticationConfiguration
            {
                InheritHostClientIdentity = true,
                EnableSessionToken        = false,
                RequireSsl = false// only for testing
            };

            // authConfig.AddBasicAuthentication()

            config.MessageHandlers.Add(new AuthenticationHandler(authConfig));
        }
Ejemplo n.º 46
0
 public static void Register(System.Web.Http.HttpConfiguration config)
 {
     config.EnableCors();
     // Web API configuration and services
     // Web API routes
     config.MapHttpAttributeRoutes();
     config.Routes.MapHttpRoute("DefaultApi1", "api/{controller}");
     config.Routes.MapHttpRoute("DefaultApi2", "api/{controller}/{value}");
     config.Routes.MapHttpRoute("DefaultApi3", "api/{controller}/{action}/{value}");
     config.Routes.MapHttpRoute("DefaultApi4", "api/{controller}/{value1}/{value2}/{value3}", new { value1 = RouteParameter.Optional, value2 = RouteParameter.Optional, value3 = RouteParameter.Optional });
     //Dim appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(Function(t) t.MediaType = "application/xml")
     //config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType)
 }
Ejemplo n.º 47
0
        /// <summary>
        /// OWIN start up method
        /// </summary>
        /// <param name="app">The app.</param>
        public void Configuration(IAppBuilder app)
        {
            var config = new System.Web.Http.HttpConfiguration();

            app.Use((context, next) =>
            {
                return(next.Invoke());
            });
            app.UseStageMarker(PipelineStage.Authenticate);
            Swashbuckle.Bootstrapper.Init(config);
            WebApiConfig.Register(config);
            app.UseWebApi(config);
            app.UseStageMarker(PipelineStage.MapHandler);
        }
        public SystemTraceHandlerTests()
        {
            _traceWriter = new TestTraceWriter(TraceLevel.Verbose);
            var config = new System.Web.Http.HttpConfiguration();
            Mock <IDependencyResolver> mockResolver = new Mock <IDependencyResolver>(MockBehavior.Strict);

            mockResolver.Setup(p => p.GetService(typeof(TraceWriter))).Returns(_traceWriter);
            config.DependencyResolver = mockResolver.Object;

            var handler = new SystemTraceHandler(config)
            {
                InnerHandler = new TestHandler()
            };

            _invoker = new HttpMessageInvoker(handler);
        }
        /// <summary>
        /// The register.
        /// </summary>
        /// <param name="config">
        /// The config.
        /// </param>
        /// <exception cref="ArgumentNullException">If any issues with configuration.
        /// </exception>
        public override void Register(System.Web.Http.HttpConfiguration config)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            base.Register(config);

            // Web API routes
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "V1/api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
        }
        protected static HttpActionContext CreateActionContext(MethodInfo action, System.Web.Http.HttpConfiguration config = null)
        {
            config = config ?? new System.Web.Http.HttpConfiguration();
            var actionContext        = new HttpActionContext();
            var controllerDescriptor = new HttpControllerDescriptor(config, action.ReflectedType.Name, action.ReflectedType);
            var controllerContext    = new HttpControllerContext();

            controllerContext.ControllerDescriptor = controllerDescriptor;
            actionContext.ControllerContext        = controllerContext;
            var actionDescriptor = new ReflectedHttpActionDescriptor(controllerDescriptor, action);

            actionContext.ActionDescriptor  = actionDescriptor;
            controllerContext.Configuration = config;

            return(actionContext);
        }
Ejemplo n.º 51
0
        public void Configuration(IAppBuilder app)
        {
            System.Web.Http.HttpConfiguration config = new System.Web.Http.HttpConfiguration();

            ConfigureOAuth(app);

            WebApiConfig.Register(config);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(config);



#if DEBUG
            Database.SetInitializer(new MigrateDatabaseToLatestVersion <AuthContext, Migrations.Configuration>());
#endif
        }
Ejemplo n.º 52
0
        /// <summary>
        /// Setup OData http://blogs.msdn.com/b/alexj/archive/2012/08/15/odata-support-in-asp-net-web-api.aspx
        /// </summary>
        /// <param name="config"></param>
        private static void SetupODataRoutes(System.Web.Http.HttpConfiguration config)
        {
            var modelBuilder = new System.Web.Http.OData.Builder.ODataConventionModelBuilder();

            modelBuilder.EntitySet <Member>("Members");

            var model = modelBuilder.GetEdmModel();

            // Create the OData formatter and give it the model
            var odataFormatter = new System.Web.Http.OData.Formatter.ODataMediaTypeFormatter(model);

            // Register the OData formatter
            config.Formatters.Insert(0, odataFormatter);

            //Next you need to setup some routes to handle common OData requests, below are the routes required for a Read/Write OData model built using the OData Routing conventions that also supports client side code-generation (vital if you want a WCF DS client application to talk to your service).

            // Metadata routes to support $metadata and code generation in the WCF Data Service client.
            config.Routes.MapHttpRoute(
                System.Web.Http.OData.Builder.Conventions.ODataRouteNames.Metadata,
                "api/$metadata",
                new { Controller = "ODataMetadata", Action = "GetMetadata" }
                );
            config.Routes.MapHttpRoute(
                System.Web.Http.OData.Builder.Conventions.ODataRouteNames.ServiceDocument,
                "api",
                new { Controller = "ODataMetadata", Action = "GetServiceDocument" }
                );

            // Relationship routes (notice the parameters is {type}Id not id, this avoids colliding with GetById(id)).
            // This code handles requests like ~/ProductFamilies(1)/Products
            config.Routes.MapHttpRoute(System.Web.Http.OData.Builder.Conventions.ODataRouteNames.PropertyNavigation,
                                       "api/{controller}({parentId})/{navigationProperty}");

            // Route for manipulating links, the code allows people to create and delete relationships between entities
            config.Routes.MapHttpRoute(System.Web.Http.OData.Builder.Conventions.ODataRouteNames.Link,
                                       "api/{controller}({id})/$links/{navigationProperty}");

            // Routes for urls both producing and handling urls like ~/Product(1), ~/Products() and ~/Products
            config.Routes.MapHttpRoute(System.Web.Http.OData.Builder.Conventions.ODataRouteNames.GetById,
                                       "api/{controller}({id})");
            config.Routes.MapHttpRoute(
                System.Web.Http.OData.Builder.Conventions.ODataRouteNames.DefaultWithParentheses, "api/{controller}()");
            config.Routes.MapHttpRoute(System.Web.Http.OData.Builder.Conventions.ODataRouteNames.Default,
                                       "api/{controller}");
        }
        public async Task PostRequestTestTest_RoutingTest()
        {
            var config = new System.Web.Http.HttpConfiguration();

            WebApiConfig.Register(config);
            string url     = "http://localhost/api/requesttests/";
            var    request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, new Uri(url));

            using (var server = new HttpServer(config))
            {
                var client = new System.Net.Http.HttpClient(server);

                using (var response = await client.SendAsync(request))
                {
                    Assert.IsTrue(System.Net.HttpStatusCode.NotFound != response.StatusCode);
                }
            }
        }
Ejemplo n.º 54
0
        public static void RegisterComponents(System.Web.Http.HttpConfiguration config)
        {
            var container = new UnityContainer();

            var cnString = ConfigurationManager.ConnectionStrings["Login"].ConnectionString;
            var pepper   = ConfigurationManager.AppSettings["Pepper"];

            container.RegisterInstance <IAccountRepository>(new AccountRepository(cnString, pepper));

            // Dependency Injection trouble-shooting.
            //http://stackoverflow.com/questions/24254189/make-sure-that-the-controller-has-a-parameterless-public-constructor-error

            // register repositories
            var defaultConnectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;

            container.RegisterInstance <ICommonRepository>(new CommonRepository(defaultConnectionString));
            container.RegisterInstance <ITeamRepository>(new TeamRepository(defaultConnectionString));
            container.RegisterInstance <IChurchRepository>(new ChurchRepository(defaultConnectionString));
            container.RegisterInstance <ILogger>(new LoggerRepository(defaultConnectionString));
            container.RegisterInstance <IMemberRepository>(new MemberRepository(defaultConnectionString));
            container.RegisterInstance <IMessageRepository>(new MessageRepository(defaultConnectionString));
            container.RegisterInstance <IReportsRepository>(new ReportsRepository(defaultConnectionString));
            container.RegisterInstance <IImportRepository>(new ImportRepository(defaultConnectionString));

            container.RegisterInstance <IImportService>(new ImportService(defaultConnectionString,
                                                                          container.Resolve <IChurchRepository>(),
                                                                          container.Resolve <ITeamRepository>(),
                                                                          container.Resolve <IMemberRepository>(),
                                                                          container.Resolve <IMessageRepository>(),
                                                                          container.Resolve <ICommonRepository>(),
                                                                          container.Resolve <ILogger>(),
                                                                          container.Resolve <IImportRepository>()));

            // register controllers
            container.RegisterType <AccountController>();
            container.RegisterType <ChurchController>();
            container.RegisterType <MembersController>();
            //container.RegisterType<MessageApiController>();

            //GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
            config.DependencyResolver = new UnityDependencyResolver(container);
        }
        public async Task PostRequestTestTest_InvalidJson_IntegrationTest()
        {
            var config = new System.Web.Http.HttpConfiguration();

            WebApiConfig.Register(config);
            string url     = "http://localhost/api/requesttests/";
            var    request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, new Uri(url));

            request.Content = new System.Net.Http.StringContent(@"{'Id':1, 'Name':''}");

            request.Content.Headers.ContentType.MediaType = "application/json";
            using (var server = new HttpServer(config))
            {
                var client = new System.Net.Http.HttpClient(server);

                using (var response = await client.SendAsync(request))
                {
                    Assert.AreEqual(System.Net.HttpStatusCode.BadRequest, response.StatusCode);
                }
            }
        }
Ejemplo n.º 56
0
        private HttpConfiguration ConfigureWebApi()
        {
            var config = new System.Web.Http.HttpConfiguration();
            var enableCorsAttribute = new EnableCorsAttribute("*", "*", "*");

            config.EnableCors(enableCorsAttribute);
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeWithQualityHeaderValue("text/html")
                                                                    );
            config.Formatters.Remove(config.Formatters.XmlFormatter);
            config.Formatters.JsonFormatter.AddUriPathExtensionMapping("json", "application/json");

            config.MapHttpAttributeRoutes();

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

            return(config);
        }
Ejemplo n.º 57
0
    public static void Register(System.Web.Http.HttpConfiguration config)
    {
        var unity = new UnityContainer();

        unity.RegisterType <SettingsController>();
        unity.RegisterType <PostsController>();
        unity.RegisterType <PagesController>();
        unity.RegisterType <BlogsController>();
        unity.RegisterType <StatsController>();
        unity.RegisterType <PackagesController>();
        unity.RegisterType <LookupsController>();
        unity.RegisterType <CommentsController>();
        unity.RegisterType <TrashController>();
        unity.RegisterType <TagsController>();
        unity.RegisterType <CategoriesController>();
        unity.RegisterType <CustomFieldsController>();
        unity.RegisterType <UsersController>();
        unity.RegisterType <RolesController>();
        unity.RegisterType <FileManagerController>();
        unity.RegisterType <CommentFilterController>();

        unity.RegisterType <ISettingsRepository, SettingsRepository>(new HierarchicalLifetimeManager());
        unity.RegisterType <IPostRepository, PostRepository>(new HierarchicalLifetimeManager());
        unity.RegisterType <IPageRepository, PageRepository>(new HierarchicalLifetimeManager());
        unity.RegisterType <IBlogRepository, BlogRepository>(new HierarchicalLifetimeManager());
        unity.RegisterType <IStatsRepository, StatsRepository>(new HierarchicalLifetimeManager());
        unity.RegisterType <IPackageRepository, PackageRepository>(new HierarchicalLifetimeManager());
        unity.RegisterType <ILookupsRepository, LookupsRepository>(new HierarchicalLifetimeManager());
        unity.RegisterType <ICommentsRepository, CommentsRepository>(new HierarchicalLifetimeManager());
        unity.RegisterType <ITrashRepository, TrashRepository>(new HierarchicalLifetimeManager());
        unity.RegisterType <ITagRepository, TagRepository>(new HierarchicalLifetimeManager());
        unity.RegisterType <ICategoryRepository, CategoryRepository>(new HierarchicalLifetimeManager());
        unity.RegisterType <ICustomFieldRepository, CustomFieldRepository>(new HierarchicalLifetimeManager());
        unity.RegisterType <IUsersRepository, UsersRepository>(new HierarchicalLifetimeManager());
        unity.RegisterType <IRolesRepository, RolesRepository>(new HierarchicalLifetimeManager());
        unity.RegisterType <IFileManagerRepository, FileManagerRepository>(new HierarchicalLifetimeManager());
        unity.RegisterType <ICommentFilterRepository, CommentFilterRepository>(new HierarchicalLifetimeManager());

        config.DependencyResolver = new IoCContainer(unity);
    }
Ejemplo n.º 58
0
        public static void Register(System.Web.Http.HttpConfiguration config)
        {
            // Web-API-Konfiguration und -Dienste

            // Web-API-Routen
            config.MapHttpAttributeRoutes();

            //ODataModelBuilder builder = new ODataConventionModelBuilder();
            //builder.EntitySet<Contracts.IResident>("Residents");
            //config.AddODataQueryFilter(new System.Web.Http.Filters.ActionFilterAttribute() );
            //config.Routes.MapODataRoute("ODataRoute", "odata", GetEdmModel());

            //ODataModelBuilder builder = new ODataConventionModelBuilder();
            //builder.EntitySet<Models.ResidentViewModel>("Residents");
            //config.MapODataServiceRoute(
            //    routeName: "ODataRoute",
            //    routePrefix: "odata",
            //    model: builder.GetEdmModel());

            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();

            builder.EntitySet <Models.ResidentViewModel>("ResidentViewModels");
            config.AddODataQueryFilter();
            //config.MapODataServiceRoute(routeName: "oDataRoute", routePrefix: "odata", model: builder.GetEdmModel());
            config.MapODataServiceRoute(routeName: "oDataRoute", routePrefix: "odata", model: builder.GetEdmModel());

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

            //config.MapODataServiceRoute( "odata", null, GetEdmModel(), new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer));



            config.EnsureInitialized();
        }
Ejemplo n.º 59
0
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888

            // Enable the application to use bearer tokens to authenticate users
            PublicClientId = "self";
            OAuthAuthorizationServerOptions aAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider          = new ApplicationOAuthProvider(PublicClientId),
                //AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                AllowInsecureHttp         = true
            };

            app.UseOAuthBearerTokens(aAuthOptions);


            var apiConfig = new System.Web.Http.HttpConfiguration();

            apiConfig.SuppressDefaultHostAuthentication();
            apiConfig.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
            apiConfig.MapHttpAttributeRoutes();
            apiConfig.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            app.UseWebApi(apiConfig);

            //app.Run(context =>
            //{
            //    //context.Response.ContentType = "plain/html";
            //    return context.Response.WriteAsync("Hello World!");
            //});
        }
Ejemplo n.º 60
0
        /// <summary>
        /// Used to call static functions when the plugin is initially loaded into
        /// the framework
        /// </summary>
        /// <param name="config"></param>
        public override void Configure(System.Web.Http.HttpConfiguration config)
        {
            base.Configure(config);

            ConfigSettings.AutoMapperConfiguration.Configure();
        }