C# (CSharp) System.Web.Http. HttpConfiguration Code Examples

C# (CSharp) System.Web.Http.HttpConfiguration - 30 примеров найдено. Это лучшие примеры C# (CSharp) кода для System.Web.Http.HttpConfiguration, полученные из open source проектов. Вы можете ставить оценку каждому примеру, чтобы помочь нам улучшить качество примеров.
Основные методы
Пример #1
0
        public Generator(HttpConfiguration conf, HttpRequestMessage req)
        {
            config = conf;
            request = req;

            GenerateRouteData();
        }
Пример #2
0
        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");
        }
Пример #3
0
        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");
        }
Пример #4
0
        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);
        }
Пример #5
0
 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());
 }
Пример #6
0
 public static void Register(HttpConfiguration config) {
     config.Routes.MapHttpRoute(
         name: "DefaultApi",
         routeTemplate: "api/{controller}/{id}",
         defaults: new {id = RouteParameter.Optional}
         );
 }
Пример #7
0
        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());
        }
        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);
            }
        }
Пример #9
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();
        }
 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));
 }
Пример #11
0
        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 }
            );
        }
Пример #12
0
        // 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(
        }
Пример #13
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 }
            //);

            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();
        }
Пример #14
0
        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
            };
        }
Пример #15
0
        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();
        }
Пример #16
0
        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 }
            );
        }
Пример #17
0
        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>();
        }
Пример #18
0
 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();
 }
Пример #19
0
        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();
        }
Пример #20
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());
        }
Пример #21
0
        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 }
            );
        }
        [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);
        }
        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 }
                );
        }
Пример #24
0
 public void Configuration(IAppBuilder app)
 {
     var config = new HttpConfiguration();
     ConfigureOAuth(app);
     WebApiConfig.Register(config);
     app.UseWebApi(config);
 }
Пример #25
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) });
        }
Пример #26
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);
        }
        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();
        }
Пример #28
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());
        }
Пример #29
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();
        }
Пример #30
0
        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 }
            );
        }