本文整理汇总了C#中System.Net.Http.HttpRequestMessage.SetRouteData方法的典型用法代码示例。如果您正苦于以下问题:C# HttpRequestMessage.SetRouteData方法的具体用法?C# HttpRequestMessage.SetRouteData怎么用?C# HttpRequestMessage.SetRouteData使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Http.HttpRequestMessage
的用法示例。
在下文中一共展示了HttpRequestMessage.SetRouteData方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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);
}
示例2: SendAsync
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// Lookup route data, or if not found as a request property then we look it up in the route table
IHttpRouteData routeData = request.GetRouteData();
if (routeData == null)
{
routeData = _configuration.Routes.GetRouteData(request);
if (routeData != null)
{
request.SetRouteData(routeData);
}
else
{
request.Properties.Add(HttpPropertyKeys.NoRouteMatched, true);
return TaskHelpers.FromResult(request.CreateErrorResponse(
HttpStatusCode.NotFound,
Error.Format(SRResources.ResourceNotFound, request.RequestUri),
SRResources.NoRouteData));
}
}
routeData.RemoveOptionalRoutingParameters();
// routeData.Route could be null if user adds a custom route that derives from System.Web.Routing.Route explicitly
// and add that to the RouteCollection in the web hosted case
var invoker = (routeData.Route == null || routeData.Route.Handler == null) ?
_defaultInvoker : new HttpMessageInvoker(routeData.Route.Handler, disposeHandler: false);
return invoker.SendAsync(request, cancellationToken);
}
示例3: initRequest
public HttpRequestMessage initRequest(string controllerName)
{
HttpRequestMessage Request = new HttpRequestMessage();
HttpConfiguration config = new HttpConfiguration();
IHttpRoute route = config.Routes.MapHttpRoute(controllerName, "api/{controller}/{id}");
HttpRouteData routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", controllerName } });
Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
Request.Properties["requestId"] = new Guid().ToString();
Request.SetRouteData(routeData);
return Request;
}
示例4: RouteContext
public RouteContext(HttpConfiguration config, HttpRequestMessage request)
{
var routeData = config.Routes.GetRouteData(request);
request.SetRouteData(routeData);
var controllerSelector = new DefaultHttpControllerSelector(config);
var descriptor = controllerSelector.SelectController(request);
ControllerType = descriptor.ControllerType;
var actionSelector = new ApiControllerActionSelector();
_actionMappings = actionSelector.GetActionMapping(descriptor).SelectMany(x => x).Where(x => x.SupportedHttpMethods.Contains(request.Method));
}
示例5: GetControllerName_PicksNull_EmptyRouteData
public void GetControllerName_PicksNull_EmptyRouteData()
{
// Arrange
HttpRequestMessage request = new HttpRequestMessage();
request.SetRouteData(GetRouteData());
DefaultHttpControllerSelector selector = new DefaultHttpControllerSelector(new HttpConfiguration());
// Act
string selectedControllerName = selector.GetControllerName(request);
// Assert
Assert.Null(selectedControllerName);
}
示例6: Can_make_uri_for_v2
public void Can_make_uri_for_v2()
{
var req = new HttpRequestMessage(HttpMethod.Get, "http://example.org/MultipleRouteTests/v2");
req.SetRequestContext(new HttpRequestContext
{
VirtualPathRoot = "/"
});
req.SetRouteData(_config.Routes.GetRouteData(req));
req.SetConfiguration(_config);
var uriMaker = _factory.NewUriMakerFor<MultipleRouteTests.MultipleRouteResourceController>(req);
var uri = uriMaker.UriFor(c => c.GetById(123));
Assert.Equal("http://example.org/MultipleRouteTests/v2/123", uri.ToString());
}
示例7: GetControllerName_PicksControllerNameFromRouteData
public void GetControllerName_PicksControllerNameFromRouteData(string controllerKeyName, string controllerName)
{
// Arrange
HttpRequestMessage request = new HttpRequestMessage();
IHttpRouteData routeData = GetRouteData();
routeData.Values[controllerKeyName] = controllerName;
request.SetRouteData(routeData);
DefaultHttpControllerSelector selector = new DefaultHttpControllerSelector(new HttpConfiguration());
// Act
string selectedControllerName = selector.GetControllerName(request);
// Assert
Assert.Equal(controllerName, selectedControllerName);
}
示例8: RedirectController
private void RedirectController(HttpRequestMessage theRequest, string theRequestedApiVersion)
{
// remove version segment, the goal is to matched to the default(no-version) route
theRequest.Properties.Add("Moodys_OriginalUri", theRequest.RequestUri);
theRequest.RequestUri = new Uri(theRequest.RequestUri.AbsoluteUri.Replace("/v" + theRequestedApiVersion + "/", "/"));
// remove routingContext
theRequest.Properties.Remove("MS_RoutingContext");
// re-generate routeData
var aNewRouteData = configuration.Routes.GetRouteData(theRequest);
// set the new routeData to request
theRequest.SetRouteData(aNewRouteData);
}
示例9: GetCorsPolicyProvider_Preflight_ReturnsExpectedPolicyProvider
public void GetCorsPolicyProvider_Preflight_ReturnsExpectedPolicyProvider(string httpMethod, string path, Type expectedProviderType)
{
AttributeBasedPolicyProviderFactory providerFactory = new AttributeBasedPolicyProviderFactory();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, "http://localhost/sample" + path);
request.Headers.Add("Origin", "http://localhost");
request.Headers.Add(CorsConstants.AccessControlRequestMethod, httpMethod);
HttpConfiguration config = new HttpConfiguration();
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.True(request.GetCorsRequestContext().IsPreflight);
Assert.IsType(expectedProviderType, provider);
}
示例10: GetCorsPolicyProvider_Preflight_NoHttpConfiguration_Throws
public void GetCorsPolicyProvider_Preflight_NoHttpConfiguration_Throws()
{
AttributeBasedPolicyProviderFactory providerFactory = new AttributeBasedPolicyProviderFactory();
// No HttpConfiguration set on the request.
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, "http://localhost/sample");
request.Headers.Add("Origin", "http://localhost");
request.Headers.Add(CorsConstants.AccessControlRequestMethod, "GET");
HttpConfiguration config = new HttpConfiguration();
IHttpRoute route = config.Routes.MapHttpRoute("default", "{controller}/{id}", new { id = RouteParameter.Optional });
request.SetRouteData(route.GetRouteData("/", request));
Assert.Throws<InvalidOperationException>(() =>
providerFactory.GetCorsPolicyProvider(request),
"The request does not have an associated configuration object.");
}
示例11: GetVirtualPath_GetsValuesInCaseInsensitiveWay
public void GetVirtualPath_GetsValuesInCaseInsensitiveWay(string controllerKey)
{
var route = new HttpRoute("{controller}");
var request = new HttpRequestMessage();
request.SetRouteData(
new HttpRouteData(route, new HttpRouteValueDictionary() {
{ "controller", "Employees" }
}));
var values = new HttpRouteValueDictionary()
{
{ "httproute", true },
{ controllerKey, "Customers" }
};
IHttpVirtualPathData virtualPath = route.GetVirtualPath(request, values);
Assert.NotNull(virtualPath);
Assert.Equal("Customers", virtualPath.VirtualPath);
}
示例12: Get
public IEnumerable<string> Get()
{
string routeTemplate = "weather/{areacode}/{days}";
IHttpRoute route = new HttpRoute(routeTemplate);
route.Defaults.Add("days", 2);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "/");
IHttpVirtualPathData pathData;
//1. 不能提供路由变量areacode的值
Dictionary<string, object> values = new Dictionary<string, object>();
pathData = route.GetVirtualPath(request, values);
yield return pathData == null ? "N/A" : pathData.VirtualPath;
//2. values无Key为"httproute"的元素
values.Add("areaCode", "028");
pathData = route.GetVirtualPath(request, values);
yield return pathData == null ? "N/A" : pathData.VirtualPath;
//3. 所有的路由变量值通过values提供
values.Add("httproute", true);
values.Add("days", 3);
IHttpRouteData routeData = new HttpRouteData(route);
routeData.Values.Add("areacode", "0512");
routeData.Values.Add("days", 4);
request.SetRouteData(routeData);
pathData = route.GetVirtualPath(request, values);
yield return pathData == null ? "N/A" : pathData.VirtualPath;
//4. 所有的路由变量值通过request提供
values.Clear();
values.Add("httproute", true);
pathData = route.GetVirtualPath(request, values);
yield return pathData == null ? "N/A" : pathData.VirtualPath;
//5. 采用定义在HttpRoute上的默认值(days = 2)
routeData.Values.Remove("days");
pathData = route.GetVirtualPath(request, values);
yield return pathData == null ? "N/A" : pathData.VirtualPath;
}
示例13: SendAsync
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
//var content = request.Content;
//string jsonContent = content.ReadAsStringAsync().Result;
//ApiRequestData data = JsonConvert.DeserializeObject<ApiRequestData>(jsonContent);
IEnumerable<string> actions;
request.Headers.TryGetValues("action", out actions);
if (actions != null && actions.Any())
{
string action = actions.FirstOrDefault();
ApiConfiguration actionConfig = ApiConfigurationMgr.Instanse.GetByKey(action);
if (actionConfig != null)
{
IHttpRouteData routeData = request.GetRouteData();
routeData.Values["controller"] = actionConfig.Controller;
routeData.Values["action"] = actionConfig.Action;
request.SetRouteData(routeData);
}
}
return base.SendAsync(request, cancellationToken);
}
示例14: WebApiTest
public WebApiTest()
{
var routeData = Substitute.For<IHttpRouteData>();
var routeValues = new Dictionary<string, object> {{"controller", CurrentController}};
routeData.Values.Returns(routeValues);
routeData.Route.Returns(Substitute.For<IHttpRoute>());
Configuration = new HttpConfiguration();
Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
Routes = Configuration.Routes;
RequestMessage = new HttpRequestMessage(RequestMethod, RequestUri);
RequestContext = new TestHttpRequestContext(RequestMessage) {Configuration = Configuration};
RequestMessage.SetRequestContext(RequestContext);
RequestMessage.SetConfiguration(Configuration);
RequestMessage.SetRouteData(routeData);
ControllerContext = new HttpControllerContext(Configuration, routeData, RequestMessage);
ControllerDescriptor = Substitute.For<HttpControllerDescriptor>(Configuration, CurrentController, typeof (DummyController));
ActionDescriptor = Substitute.For<HttpActionDescriptor>(ControllerDescriptor);
ActionContext = new HttpActionContext(ControllerContext, ActionDescriptor);
}
示例15: HandleActualRequestAsync
private async Task<HttpResponseMessage> HandleActualRequestAsync(GetRequest request)
{
var query = "";
if (request.Query != null)
query = request.Query.TrimStart('?').Replace("+", "%2B");
string indexQuery = null;
string modifiedQuery;
// to avoid UriFormatException: Invalid URI: The Uri string is too long. [see RavenDB-1517]
if (query.Length > 32760 && TryExtractIndexQuery(query, out modifiedQuery, out indexQuery))
{
query = modifiedQuery;
}
var msg = new HttpRequestMessage(HttpMethod.Get, new UriBuilder
{
Host = "multi.get",
Query = query,
Path = request.Url
}.Uri);
msg.SetConfiguration(Configuration);
var route = Configuration.Routes.GetRouteData(msg);
msg.SetRouteData(route);
var controllerSelector = new DefaultHttpControllerSelector(Configuration);
var descriptor = controllerSelector.SelectController(msg);
foreach (var header in request.Headers)
{
msg.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
msg.Headers.TryAddWithoutValidation("Raven-internal-request", "true");
var controller = (RavenBaseApiController)descriptor.CreateController(msg);
controller.Configuration = Configuration;
var controllerContext = new HttpControllerContext(Configuration, route, msg)
{
ControllerDescriptor = descriptor,
Controller = controller,
RequestContext = new HttpRequestContext(),
RouteData = route
};
controller.SkipAuthorizationSinceThisIsMultiGetRequestAlreadyAuthorized = true;
controller.ControllerContext = controllerContext;
controllerContext.Request = msg;
controller.RequestContext = controllerContext.RequestContext;
controller.Configuration = Configuration;
if (string.IsNullOrEmpty(indexQuery) == false && (controller as RavenDbApiController) != null)
{
((RavenDbApiController)controller).SetPostRequestQuery(indexQuery);
}
return await controller.ExecuteAsync(controllerContext, CancellationToken.None);
}