本文整理匯總了C#中System.Net.Http.HttpRequestMessage.SetConfiguration方法的典型用法代碼示例。如果您正苦於以下問題:C# HttpRequestMessage.SetConfiguration方法的具體用法?C# HttpRequestMessage.SetConfiguration怎麽用?C# HttpRequestMessage.SetConfiguration使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類System.Net.Http.HttpRequestMessage
的用法示例。
在下文中一共展示了HttpRequestMessage.SetConfiguration方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: Match_UsesODataDefaultRoutingConventions_IfControllerFound
public void Match_UsesODataDefaultRoutingConventions_IfControllerFound(string expectedControllerName,
string entitySetName)
{
// Arrange
const string routeName = "api";
var request = new HttpRequestMessage(HttpMethod.Get, "http://any/" + entitySetName);
var routeCollection = new HttpRouteCollection { { routeName, new HttpRoute() } };
var config = new HttpConfiguration(routeCollection);
request.SetConfiguration(config);
var pathHandler = new DefaultODataPathHandler();
var model = GetEdmModel();
config.MapHttpAttributeRoutes();
var conventions = config.CreateODataDomainRoutingConventions<NorthwindDomainController>(model);
var constraint = new DefaultODataPathRouteConstraint(pathHandler, model, routeName, conventions);
config.EnsureInitialized();
var values = new Dictionary<string, object>
{
{ ODataRouteConstants.ODataPath, entitySetName },
};
// Act
var matched = constraint.Match(request, route: null, parameterName: null, values: values,
routeDirection: HttpRouteDirection.UriResolution);
// Assert
Assert.True(matched);
Assert.Equal(expectedControllerName, values[ODataRouteConstants.Controller]);
}
示例2: GenerateActionLink_GeneratesLinkWithCast_IfEntitySetTypeDoesnotMatchActionEntityType
public void GenerateActionLink_GeneratesLinkWithCast_IfEntitySetTypeDoesnotMatchActionEntityType()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
var vehicles = builder.EntitySet<Vehicle>("vehicles");
var car = builder.Entity<Car>();
var paintAction = car.Action("Paint");
IEdmModel model = builder.GetEdmModel();
var vehiclesEdmSet = model.EntityContainers().Single().FindEntitySet("vehicles");
var carEdmType = model.FindDeclaredType("System.Web.Http.OData.Builder.TestModels.Car") as IEdmEntityType;
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);
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 = ActionLinkGenerationConvention.GenerateActionLink(entityContext, paintAction);
Assert.Equal("http://localhost/vehicles(Model=2009,Name='Accord')/System.Web.Http.OData.Builder.TestModels.Car/Paint", link.AbsoluteUri);
}
示例3: GetCorsPolicyProvider_Preflight_ReturnsCompleteControllerContext
public void GetCorsPolicyProvider_Preflight_ReturnsCompleteControllerContext()
{
// Arrange
AttributeBasedPolicyProviderFactory providerFactory = new AttributeBasedPolicyProviderFactory();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, "http://localhost/sample");
request.Headers.Add("Origin", "http://localhost");
request.Headers.Add(CorsConstants.AccessControlRequestMethod, "POST");
HttpConfiguration config = new HttpConfiguration();
HttpControllerContext controllerContext = null;
var actionSelector = new Mock<IHttpActionSelector>();
actionSelector.Setup(s => s.SelectAction(It.IsAny<HttpControllerContext>()))
.Callback<HttpControllerContext>(context => controllerContext = context);
config.Services.Replace(typeof(IHttpActionSelector), actionSelector.Object);
request.SetConfiguration(config);
IHttpRoute route = config.Routes.MapHttpRoute("default", "{controller}/{id}", new { id = RouteParameter.Optional });
request.SetRouteData(route.GetRouteData("/", request));
ICorsPolicyProvider provider = providerFactory.GetCorsPolicyProvider(request);
// Assert
Assert.NotNull(controllerContext);
Assert.Equal(config, controllerContext.Configuration);
Assert.NotNull(controllerContext.Request);
Assert.NotNull(controllerContext.RequestContext);
Assert.NotNull(controllerContext.Controller);
Assert.NotNull(controllerContext.ControllerDescriptor);
}
示例4: HandleRequestAsync
public async Task<HttpResponseMessage> HandleRequestAsync(FunctionDescriptor function, HttpRequestMessage request, Func<HttpRequestMessage, Task<HttpResponseMessage>> invokeFunction)
{
// First check if there is a registered WebHook Receiver for this request, and if
// so use it
HttpTriggerBindingMetadata httpFunctionMetadata = (HttpTriggerBindingMetadata)function.Metadata.InputBindings.FirstOrDefault(p => p.Type == BindingType.HttpTrigger);
string webHookReceiver = httpFunctionMetadata.WebHookType;
IWebHookReceiver receiver = null;
if (string.IsNullOrEmpty(webHookReceiver) || !_receiverLookup.TryGetValue(webHookReceiver, out receiver))
{
// The function is not correctly configured. Log an error and return 500
string configurationError = string.Format(CultureInfo.InvariantCulture, "Invalid WebHook configuration. Unable to find a receiver for WebHook type '{0}'", webHookReceiver);
function.Invoker.OnError(new FunctionInvocationException(configurationError));
return new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError);
}
HttpRequestContext context = new HttpRequestContext
{
Configuration = _httpConfiguration
};
request.SetConfiguration(_httpConfiguration);
// add the anonymous handler function from above to the request properties
// so our custom WebHookHandler can invoke it at the right time
request.Properties.Add(AzureFunctionsCallbackKey, invokeFunction);
// Request content can't be read multiple
// times, so this forces it to buffer
await request.Content.LoadIntoBufferAsync();
string receiverId = function.Name.ToLowerInvariant();
return await receiver.ReceiveAsync(receiverId, context, request);
}
示例5: Convention_GeneratesUri_ForActionBoundToEntity
public void Convention_GeneratesUri_ForActionBoundToEntity()
{
// Arrange
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Customer>("Customers");
var action = builder.EntityType<Customer>().Action("MyAction");
action.Parameter<string>("param");
IEdmModel model = builder.GetEdmModel();
// Act
HttpConfiguration configuration = new HttpConfiguration();
configuration.MapODataServiceRoute("odata", "odata", model);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:123");
request.SetConfiguration(configuration);
request.ODataProperties().RouteName = "odata";
IEdmEntitySet customers = model.EntityContainer.FindEntitySet("Customers");
var edmType = model.SchemaElements.OfType<IEdmEntityType>().First(e => e.Name == "Customer");
var serializerContext = new ODataSerializerContext { Model = model, NavigationSource = customers, Url = request.GetUrlHelper() };
var entityContext = new EntityInstanceContext(serializerContext, edmType.AsReference(), new Customer { Id = 109 });
// Assert
var edmAction = model.SchemaElements.OfType<IEdmAction>().First(f => f.Name == "MyAction");
Assert.NotNull(edmAction);
ActionLinkBuilder actionLinkBuilder = model.GetActionLinkBuilder(edmAction);
Uri link = actionLinkBuilder.BuildActionLink(entityContext);
Assert.Equal("http://localhost:123/odata/Customers(109)/Default.MyAction", link.AbsoluteUri);
}
示例6: HandleRequestAsync
public async Task<HttpResponseMessage> HandleRequestAsync(FunctionDescriptor function, HttpRequestMessage request, Func<HttpRequestMessage, Task<HttpResponseMessage>> invokeFunction)
{
// First check if there is a registered WebHook Receiver for this request, and if
// so use it
HttpBindingMetadata httpFunctionMetadata = (HttpBindingMetadata)function.Metadata.InputBindings.FirstOrDefault(p => p.Type == BindingType.HttpTrigger);
string webHookReceiver = httpFunctionMetadata.WebHookType;
IWebHookReceiver receiver = null;
if (string.IsNullOrEmpty(webHookReceiver) || !_receiverLookup.TryGetValue(webHookReceiver, out receiver))
{
// If the function is a not a correctly configured WebHook return 500
return new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError);
}
HttpRequestContext context = new HttpRequestContext
{
Configuration = _httpConfiguration
};
request.SetConfiguration(_httpConfiguration);
// add the anonymous handler function from above to the request properties
// so our custom WebHookHandler can invoke it at the right time
request.Properties.Add(AzureFunctionsCallbackKey, invokeFunction);
// TODO: Is there a better way? Requests content can't be read multiple
// times, so this forces it to buffer
await request.Content.ReadAsStringAsync();
string receiverId = function.Name.ToLowerInvariant();
return await receiver.ReceiveAsync(receiverId, context, request);
}
示例7: Apply_Doesnot_Override_UserConfiguration
public void Apply_Doesnot_Override_UserConfiguration()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
var vehicles = builder.EntitySet<Vehicle>("vehicles");
var car = builder.AddEntityType(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.EntityContainer.FindEntitySet("vehicles");
var carEdmType = model.FindDeclaredType("System.Web.OData.Builder.TestModels.Car") as IEdmEntityType;
var paintEdmAction =
model.GetAvailableProcedures(
model.FindDeclaredType("System.Web.OData.Builder.TestModels.Car") as IEdmEntityType).Single()
as IEdmAction;
Assert.NotNull(paintEdmAction);
HttpConfiguration configuration = new HttpConfiguration();
configuration.Routes.MapODataServiceRoute(model);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");
request.SetConfiguration(configuration);
ActionLinkBuilder actionLinkBuilder = model.GetActionLinkBuilder(paintEdmAction);
var serializerContext = new ODataSerializerContext { Model = model, NavigationSource = vehiclesEdmSet, Url = request.GetUrlHelper() };
var entityContext = new EntityInstanceContext(serializerContext, carEdmType.AsReference(), new Car { Model = 2009, Name = "Contoso" });
Uri link = actionLinkBuilder.BuildActionLink(entityContext);
Assert.Equal("http://localhost/ActionTestWorks", link.AbsoluteUri);
}
示例8: NavigationLinksGenerationConvention_GeneratesLinksWithCast_ForDerivedProperties
public void NavigationLinksGenerationConvention_GeneratesLinksWithCast_ForDerivedProperties()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Vehicle>("vehicles");
builder.EntitySet<Manufacturer>("manufacturers");
IEdmModel model = builder.GetEdmModel();
IEdmEntitySet vehiclesEdmEntitySet = model.EntityContainer.FindEntitySet("vehicles");
IEdmEntityType carType = model.AssertHasEntityType(typeof(Car));
IEdmNavigationProperty carManufacturerProperty = carType.AssertHasNavigationProperty(model, "Manufacturer", typeof(CarManufacturer), isNullable: true, multiplicity: EdmMultiplicity.ZeroOrOne);
HttpConfiguration configuration = new HttpConfiguration();
string routeName = "Route";
configuration.Routes.MapODataServiceRoute(routeName, null, model);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");
request.SetConfiguration(configuration);
request.ODataProperties().RouteName = routeName;
NavigationSourceLinkBuilderAnnotation linkBuilder = model.GetNavigationSourceLinkBuilder(vehiclesEdmEntitySet);
var serializerContext = new ODataSerializerContext { Model = model, NavigationSource = vehiclesEdmEntitySet, Url = request.GetUrlHelper() };
var entityContext = new EntityInstanceContext(serializerContext, carType.AsReference(), new Car { Model = 2009, Name = "Accord" });
Uri uri = linkBuilder.BuildNavigationLink(entityContext, carManufacturerProperty, ODataMetadataLevel.Default);
Assert.Equal("http://localhost/vehicles(Model=2009,Name='Accord')/System.Web.OData.Builder.TestModels.Car/Manufacturer", uri.AbsoluteUri);
}
示例9: 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);
}
示例10: CreateHttpRequestMessage
private static HttpRequestMessage CreateHttpRequestMessage(HttpActionDescriptor actionDescriptor, ODataRoute oDataRoute, HttpConfiguration httpConfig)
{
Contract.Requires(httpConfig != null);
Contract.Requires(oDataRoute != null);
Contract.Requires(httpConfig != null);
Contract.Ensures(Contract.Result<HttpRequestMessage>() != null);
Contract.Assume(oDataRoute.Constraints != null);
var httpRequestMessage = new HttpRequestMessage(actionDescriptor.SupportedHttpMethods.First(), "http://any/");
var requestContext = new HttpRequestContext
{
Configuration = httpConfig
};
httpRequestMessage.SetConfiguration(httpConfig);
httpRequestMessage.SetRequestContext(requestContext);
var httpRequestMessageProperties = httpRequestMessage.ODataProperties();
Contract.Assume(httpRequestMessageProperties != null);
httpRequestMessageProperties.Model = oDataRoute.GetEdmModel();
httpRequestMessageProperties.RouteName = oDataRoute.GetODataPathRouteConstraint().RouteName;
httpRequestMessageProperties.RoutingConventions = oDataRoute.GetODataPathRouteConstraint().RoutingConventions;
httpRequestMessageProperties.PathHandler = oDataRoute.GetODataPathRouteConstraint().PathHandler;
return httpRequestMessage;
}
示例11: TryHandle
public async Task<HttpResponseMessage> TryHandle(HttpRequestMessage request, Func<HttpRequestMessage, Task<HttpResponseMessage>> invokeJobFunction)
{
// First check if there is a registered WebHook Receiver for this request, and if
// so use it
string route = request.RequestUri.LocalPath.ToLowerInvariant();
IWebHookReceiver receiver = null;
string receiverId = null;
if (TryParseReceiver(route, out receiver, out receiverId))
{
HttpRequestContext context = new HttpRequestContext
{
Configuration = _httpConfiguration
};
request.SetConfiguration(_httpConfiguration);
// add the anonymous handler function from above to the request properties
// so our custom WebHookHandler can invoke it at the right time
request.Properties.Add(WebHookJobFunctionInvokerKey, invokeJobFunction);
return await receiver.ReceiveAsync(receiverId, context, request);
}
return null;
}
示例12: GetHttpActionDescriptorForRestierController
private static HttpActionDescriptor GetHttpActionDescriptorForRestierController(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor)
{
HttpActionDescriptor actionDescriptor;
var perControllerConfig = controllerDescriptor.Configuration;
request.SetConfiguration(perControllerConfig);
var requestContext = request.GetRequestContext();
requestContext.Configuration = perControllerConfig;
requestContext.RouteData = request.GetRouteData();
requestContext.Url = new UrlHelper(request);
requestContext.VirtualPathRoot = perControllerConfig.VirtualPathRoot;
var controller = controllerDescriptor.CreateController(request);
using (controller as IDisposable)
{
var controllerContext = new HttpControllerContext(requestContext, request, controllerDescriptor, controller);
try
{
actionDescriptor = perControllerConfig.Services.GetActionSelector().SelectAction(controllerContext);
}
catch (HttpResponseException ex)
{
if (ex.Response.StatusCode == HttpStatusCode.NotFound || ex.Response.StatusCode == HttpStatusCode.MethodNotAllowed)
{
actionDescriptor = null;
}
else
{
throw;
}
}
}
return actionDescriptor;
}
示例13: ProcessBatchAsync_CallsRegisterForDispose
public void ProcessBatchAsync_CallsRegisterForDispose()
{
// Arrange
List<IDisposable> expectedResourcesForDisposal = new List<IDisposable>();
MockHttpServer server = new MockHttpServer(request =>
{
var tmpContent = new StringContent(String.Empty);
request.RegisterForDispose(tmpContent);
expectedResourcesForDisposal.Add(tmpContent);
return new HttpResponseMessage { Content = new StringContent(request.RequestUri.AbsoluteUri) };
});
UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler(server);
HttpRequestMessage batchRequest = new HttpRequestMessage(HttpMethod.Post, "http://example.com/$batch")
{
Content = new MultipartContent("mixed")
{
ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Get, "http://example.com/")),
new MultipartContent("mixed") // ChangeSet
{
ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Post, "http://example.com/"))
}
}
};
batchRequest.SetConfiguration(new HttpConfiguration());
// Act
var response = batchHandler.ProcessBatchAsync(batchRequest, CancellationToken.None).Result;
var resourcesForDisposal = batchRequest.GetResourcesForDisposal();
// Assert
foreach (var expectedResource in expectedResourcesForDisposal)
{
Assert.Contains(expectedResource, resourcesForDisposal);
}
}
示例14: SendAsync_Preflight_ReturnsAllowMethodsAndAllowHeaders
public void SendAsync_Preflight_ReturnsAllowMethodsAndAllowHeaders(string requestedMethod, string expectedOrigin, string requestedHeaders)
{
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute("default", "{controller}");
HttpServer server = new HttpServer(config);
CorsMessageHandler corsHandler = new CorsMessageHandler(config);
corsHandler.InnerHandler = server;
HttpMessageInvoker invoker = new HttpMessageInvoker(corsHandler);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, "http://localhost/sample");
request.SetConfiguration(config);
request.Headers.Add(CorsConstants.Origin, "http://localhost");
request.Headers.Add(CorsConstants.AccessControlRequestMethod, requestedMethod);
request.Headers.Add(CorsConstants.AccessControlRequestHeaders, requestedHeaders);
HttpResponseMessage response = invoker.SendAsync(request, CancellationToken.None).Result;
string origin = response.Headers.GetValues(CorsConstants.AccessControlAllowOrigin).FirstOrDefault();
string allowMethod = response.Headers.GetValues(CorsConstants.AccessControlAllowMethods).FirstOrDefault();
string[] allowHeaders = response.Headers.GetValues(CorsConstants.AccessControlAllowHeaders).FirstOrDefault().Split(',');
string[] requestedHeaderArray = requestedHeaders.Split(',');
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expectedOrigin, origin);
Assert.Equal(requestedMethod, allowMethod);
foreach (string requestedHeader in requestedHeaderArray)
{
Assert.Contains(requestedHeader, allowHeaders);
}
}
示例15: GenerateLinkDirectly_ReturnsNull_IfRouteTemplateHasParameterInPrefix
public void GenerateLinkDirectly_ReturnsNull_IfRouteTemplateHasParameterInPrefix()
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/vpath/prefix/Customers");
HttpConfiguration config = new HttpConfiguration(new HttpRouteCollection("http://localhost/vpath"));
request.SetConfiguration(config);
ODataRoute odataRoute = new ODataRoute("{prefix}", pathConstraint: null);
Assert.Null(odataRoute.GenerateLinkDirectly(request, "odataPath"));
}