本文整理汇总了C#中HttpConfiguration类的典型用法代码示例。如果您正苦于以下问题:C# HttpConfiguration类的具体用法?C# HttpConfiguration怎么用?C# HttpConfiguration使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
HttpConfiguration类属于命名空间,在下文中一共展示了HttpConfiguration类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: RegisterRoutes
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// map the MVC UI route (note the route constraint as the last controller passed in)
// http://codebetter.com/howarddierking/2011/05/09/using-serviceroute-with-existing-mvc-routes/
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Dashboard", action = "Home", id = UrlParameter.Optional }, // Parameter defaults
new { controller = new NotInValuesConstraint(new[] { "constants", "folders", "items", "itemtypes", "operations", "speech", "suggestions", "tags", "trace", "users", "OAuthHandler.ashx" }) }
);
// map the WCF WebApi service routes
HttpConfiguration config = new HttpConfiguration() { MaxBufferSize = 1024 * 1024, MaxReceivedMessageSize = 1024 * 1024 };
RouteTable.Routes.MapServiceRoute<ConstantsResource>("constants", null);
RouteTable.Routes.MapServiceRoute<FolderResource>("folders", null);
RouteTable.Routes.MapServiceRoute<ItemResource>("items", config);
RouteTable.Routes.MapServiceRoute<ItemTypeResource>("itemtypes", null);
RouteTable.Routes.MapServiceRoute<OperationResource>("operations", null);
RouteTable.Routes.MapServiceRoute<SpeechResource>("speech",
new HttpConfiguration
{
MaxReceivedMessageSize = 1048576, // 1MB == 32seconds of speech
MaxBufferSize = 1048576, // 1MB == 32seconds of speech
});
RouteTable.Routes.MapServiceRoute<SuggestionResource>("suggestions", null);
RouteTable.Routes.MapServiceRoute<TagResource>("tags", null);
RouteTable.Routes.MapServiceRoute<TraceResource>("trace", null);
RouteTable.Routes.MapServiceRoute<UserResource>("users", config);
}
示例2: BadReturnTypeThrows
public void BadReturnTypeThrows(string methodName)
{
// Arrange
ODataQueryParameterBindingAttribute attribute = new ODataQueryParameterBindingAttribute();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Customer/?$orderby=Name");
HttpConfiguration config = new HttpConfiguration();
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
HttpControllerContext controllerContext = new HttpControllerContext(config, new HttpRouteData(new HttpRoute()), request);
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), "CustomerLowLevel", typeof(CustomerHighLevelController));
MethodInfo methodInfo = typeof(CustomerLowLevelController).GetMethod(methodName);
ParameterInfo parameterInfo = methodInfo.GetParameters().First();
HttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(controllerDescriptor, methodInfo);
HttpActionContext actionContext = new HttpActionContext(controllerContext, actionDescriptor);
HttpParameterDescriptor parameterDescriptor = new ReflectedHttpParameterDescriptor(actionDescriptor, parameterInfo);
// Act
HttpParameterBinding binding = attribute.GetBinding(parameterDescriptor);
// Act & Assert
Assert.Throws<InvalidOperationException>(
() => binding.ExecuteBindingAsync((ModelMetadataProvider)null, actionContext, CancellationToken.None).Wait(),
String.Format(
"The 'ODataQueryParameterBinding' type cannot be used with action '{0}' on controller 'CustomerLowLevel' because the return type '{1}' does not specify the type of the collection.",
actionDescriptor.ActionName,
actionDescriptor.ReturnType.FullName));
}
示例3: GetEdmModelReturnsNullByDefault
public void GetEdmModelReturnsNullByDefault()
{
HttpConfiguration config = new HttpConfiguration();
IEdmModel model = config.GetEdmModel();
Assert.Null(model);
}
示例4: UseWebApi
private static void UseWebApi(IAppBuilder application, IKernel kernel)
{
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
var cors = new EnableCorsAttribute("*", "*", "*");
//GlobalConfiguration.Configure(configuration =>
//{
// configuration.SuppressDefaultHostAuthentication();
// configuration.MapHttpAttributeRoutes();
// configuration.EnableCors(cors);
// configuration.Filters.Add(new HostAuthenticationAttribute(OAuthDefaults.AuthenticationType));
// var jsonformatter = configuration.Formatters.JsonFormatter;
// jsonformatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
// configuration.AddJsonpFormatter();
// application.UseNinjectMiddleware(() => kernel);
// application.UseNinjectWebApi(configuration);
// application.UseWebApi(configuration);
//});
config.SuppressDefaultHostAuthentication();
ConfigureOAuth(application);
config.EnableCors(cors);
config.Filters.Add(new HostAuthenticationAttribute(OAuthDefaults.AuthenticationType));
var jsonformatter = config.Formatters.JsonFormatter;
jsonformatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.AddJsonpFormatter();
application.UseNinjectMiddleware(() => kernel);
application.UseNinjectWebApi(config);
application.UseWebApi(config);
application.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
}
示例5: EnumParameters_ShowUpCorrectlyOnDescription
public void EnumParameters_ShowUpCorrectlyOnDescription()
{
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute("Default", "{controller}");
DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, typeof(EnumParameterOverloadsController));
config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);
IApiExplorer explorer = config.Services.GetApiExplorer();
ApiDescription description = explorer.ApiDescriptions.FirstOrDefault(desc => desc.ActionDescriptor.ActionName == "GetWithEnumParameter");
Assert.NotNull(description);
Assert.Equal(1, description.ParameterDescriptions.Count);
Assert.Equal(ApiParameterSource.FromUri, description.ParameterDescriptions[0].Source);
Assert.Equal("EnumParameterOverloads?scope={scope}", description.RelativePath);
description = explorer.ApiDescriptions.FirstOrDefault(desc => desc.ActionDescriptor.ActionName == "GetWithTwoEnumParameters");
Assert.NotNull(description);
Assert.Equal(2, description.ParameterDescriptions.Count);
Assert.Equal(ApiParameterSource.FromUri, description.ParameterDescriptions[0].Source);
Assert.Equal(ApiParameterSource.FromUri, description.ParameterDescriptions[1].Source);
Assert.Equal("EnumParameterOverloads?level={level}&kind={kind}", description.RelativePath);
description = explorer.ApiDescriptions.FirstOrDefault(desc => desc.ActionDescriptor.ActionName == "GetWithNullableEnumParameter");
Assert.NotNull(description);
Assert.Equal(1, description.ParameterDescriptions.Count);
Assert.Equal(ApiParameterSource.FromUri, description.ParameterDescriptions[0].Source);
Assert.Equal("EnumParameterOverloads?level={level}", description.RelativePath);
}
示例6: Apply_Doesnot_Override_UserConfiguration
public void Apply_Doesnot_Override_UserConfiguration()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
var vehicles = builder.EntitySet<Vehicle>("vehicles");
var car = builder.AddEntity(typeof(Car));
var paintAction = vehicles.EntityType.Action("Paint");
paintAction.HasActionLink(ctxt => new Uri("http://localhost/ActionTestWorks"), followsConventions: false);
ActionLinkGenerationConvention convention = new ActionLinkGenerationConvention();
convention.Apply(paintAction, builder);
IEdmModel model = builder.GetEdmModel();
var vehiclesEdmSet = model.EntityContainers().Single().FindEntitySet("vehicles");
var carEdmType = model.FindDeclaredType("System.Web.Http.OData.Builder.TestModels.Car") as IEdmEntityType;
var paintEdmAction =
model.GetAvailableProcedures(
model.FindDeclaredType("System.Web.Http.OData.Builder.TestModels.Car") as IEdmEntityType).Single()
as IEdmAction;
Assert.NotNull(paintEdmAction);
HttpConfiguration configuration = new HttpConfiguration();
configuration.Routes.MapODataRoute(model);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");
request.SetConfiguration(configuration);
ActionLinkBuilder actionLinkBuilder = model.GetActionLinkBuilder(paintEdmAction);
var serializerContext = new ODataSerializerContext { Model = model, EntitySet = vehiclesEdmSet, Url = request.GetUrlHelper() };
var entityContext = new EntityInstanceContext(serializerContext, carEdmType.AsReference(), new Car { Model = 2009, Name = "Accord" });
Uri link = actionLinkBuilder.BuildActionLink(entityContext);
Assert.Equal("http://localhost/ActionTestWorks", link.AbsoluteUri);
}
示例7: WebHost_Batching_WithSpecialCharactersInUrl
public async Task WebHost_Batching_WithSpecialCharactersInUrl()
{
// Arrange
var handler = new SuccessMessageHandler();
var routeCollection = new HostedHttpRouteCollection(new RouteCollection(), "/");
routeCollection.Add("default", routeCollection.CreateRoute(
"values/ space",
defaults: null,
constraints: null,
dataTokens: null,
handler: handler));
var configuration = new HttpConfiguration(routeCollection);
var server = new HttpServer(configuration);
var batchHandler = new DefaultHttpBatchHandler(server);
var request = new HttpRequestMessage
{
Content = new MultipartContent("mixed")
{
new HttpMessageContent(new HttpRequestMessage(HttpMethod.Post, "http://contoso.com/values/ space"))
}
};
// Arrange
var response = await batchHandler.ProcessBatchAsync(request, CancellationToken.None);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.True(handler.IsCalled);
}
示例8: HttpControllerContext
public HttpControllerContext(HttpConfiguration configuration, IHttpRouteData routeData,
HttpRequestMessage request)
{
if (configuration == null)
{
throw Error.ArgumentNull("configuration");
}
if (routeData == null)
{
throw Error.ArgumentNull("routeData");
}
if (request == null)
{
throw Error.ArgumentNull("request");
}
_requestContext = new HttpRequestContext
{
Configuration = configuration,
RouteData = routeData
};
_request = request;
}
示例9: Main2
/// <summary>
/// This was a test to see how painful it is to create a large number of service hosts.
/// </summary>
/// <param name="args"></param>
public static void Main2(string[] args)
{
var serviceLocator = new ServiceLocator(CreateDIContainer());
for (int i = 0; i < 1000; i++) {
var baseurl = new Uri("http://localhost:1000/service" + i);
var config = new HttpConfiguration();
config.CreateInstance = (type, context, request) => serviceLocator.GetInstance(type);
config.RequestHandlers = (handlers, se, od ) => handlers.Add(new ServerStateOperationHandler(null));
config.ResponseHandlers = (handlers, se, od) => {
handlers.Add(new LoggingOperationHandler(new Logger()));
handlers.Add(new CompressionHandler());
};
var host = new HttpServiceHost(typeof(FooService), config, baseurl);
host.Open();
Console.WriteLine("Opening host open " + baseurl);
}
Console.WriteLine("Host open. Hit enter to exit...");
// Console.WriteLine("Use a web browser and go to " + baseurl + " or do it right and get fiddler!");
Console.Read();
// host.Close();
}
示例10: Apply_AddsFeedSelfLink_ThatThrowsForMissingRoute
public void Apply_AddsFeedSelfLink_ThatThrowsForMissingRoute()
{
// Arrange
Func<FeedContext, Uri> feedSelfLink = null;
var mockEntityType = new Mock<EntityTypeConfiguration>();
var mockEntitySet = new Mock<EntitySetConfiguration>();
mockEntitySet.Setup(entitySet => entitySet.EntityType).Returns(mockEntityType.Object);
mockEntitySet.Setup(entitySet => entitySet.HasFeedSelfLink(It.IsAny<Func<FeedContext, Uri>>()))
.Returns(mockEntitySet.Object)
.Callback<Func<FeedContext, Uri>>(selfLink => { feedSelfLink = selfLink; });
var mockModelBuilder = new Mock<ODataModelBuilder>();
HttpConfiguration configuration = new HttpConfiguration();
HttpRequestMessage request = new HttpRequestMessage();
request.Properties["MS_HttpConfiguration"] = configuration;
FeedContext context = new FeedContext(new Mock<IEdmEntitySet>().Object, new UrlHelper(request), new Product[0]);
// Act
new SelfLinksGenerationConvention().Apply(mockEntitySet.Object, mockModelBuilder.Object);
// Assert
Assert.NotNull(feedSelfLink);
Assert.ThrowsArgument(() => feedSelfLink(context), "name",
"A route named 'OData.Default' could not be found in the route collection");
}
示例11: GenerateActionLink_GeneratesLinkWithoutCast_IfEntitySetTypeMatchesActionEntityType
public void GenerateActionLink_GeneratesLinkWithoutCast_IfEntitySetTypeMatchesActionEntityType()
{
// Arrange
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
var cars = builder.EntitySet<Car>("cars");
var paintAction = cars.EntityType.Action("Paint");
IEdmModel model = builder.GetEdmModel();
var carsEdmSet = model.EntityContainers().Single().FindEntitySet("cars");
HttpConfiguration configuration = new HttpConfiguration();
string routeName = "Route";
configuration.Routes.MapODataRoute(routeName, null, model);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");
request.SetConfiguration(configuration);
request.SetODataRouteName(routeName);
// Act
Uri link = ActionLinkGenerationConvention.GenerateActionLink(
new EntityInstanceContext()
{
EdmModel = model,
EntitySet = carsEdmSet,
EntityType = carsEdmSet.ElementType,
Url = request.GetUrlHelper(),
EntityInstance = new Car { Model = 2009, Name = "Accord" }
},
paintAction);
Assert.Equal("http://localhost/cars(Model=2009,Name='Accord')/Paint", link.AbsoluteUri);
}
示例12: MapHttpAttributeRoutes
/// <summary>
/// Scans the specified assemblies for all routes defined with AttributeRouting attributes,
/// and applies configuration options against the routes found.
/// </summary>
/// <param name="routes"></param>
/// <param name="configurationAction">The initialization action that builds the configuration object</param>
public static void MapHttpAttributeRoutes(this HttpRouteCollection routes, Action<HttpConfiguration> configurationAction)
{
var configuration = new HttpConfiguration();
configurationAction.Invoke(configuration);
routes.MapHttpAttributeRoutesInternal(configuration);
}
示例13: GetModelBinderProvider
// This will get called by a parameter binding, which will cache the results.
public ModelBinderProvider GetModelBinderProvider(HttpConfiguration configuration)
{
if (BinderType != null)
{
object value = configuration.DependencyResolver.GetService(BinderType)
?? Activator.CreateInstance(BinderType);
if (value != null)
{
VerifyBinderType(value.GetType());
ModelBinderProvider result = (ModelBinderProvider)value;
return result;
}
}
// Create default over config
IEnumerable<ModelBinderProvider> providers = configuration.Services.GetModelBinderProviders();
if (providers.Count() == 1)
{
return providers.First();
}
return new CompositeModelBinderProvider(providers);
}
示例14: IsRequiredMember_ReturnsFalse_ForNullableProperties
public void IsRequiredMember_ReturnsFalse_ForNullableProperties(string propertyName)
{
HttpConfiguration config = new HttpConfiguration();
IRequiredMemberSelector selector = new ModelValidationRequiredMemberSelector(config.Services.GetModelMetadataProvider(), config.Services.GetModelValidatorProviders());
Assert.False(selector.IsRequiredMember(typeof(NullableProperties).GetProperty(propertyName)));
}
示例15: Main
static void Main(string[] args)
{
var serviceLocator = new ServiceLocator(CreateDIContainer());
var baseurl = new Uri("http://localhost:1000/");
var serverState = new ServerState();
serverState["Hello"] = "World";
var config = new HttpConfiguration();
config.CreateInstance = (type, context, request) => serviceLocator.GetInstance(type);
config.RequestHandlers = (handlers, se, od) => handlers.Add(new ServerStateOperationHandler(serverState));
config.ResponseHandlers = (handlers, se, od) => {
handlers.Add(new LoggingOperationHandler(new Logger()));
handlers.Add(new CompressionHandler());
};
config.Formatters.Insert(0, new JsonMediaTypeFormatter());
HttpServiceHost host = new HttpServiceHost(typeof(FooService), config, baseurl);
host.Open();
Console.WriteLine("Host open. Hit enter to exit...");
Console.WriteLine("Use a web browser and go to " + baseurl + " or do it right and get fiddler!");
Console.Read();
host.Close();
}