本文整理汇总了C#中System.Net.Http.HttpRequestMessage.GetRouteData方法的典型用法代码示例。如果您正苦于以下问题:C# HttpRequestMessage.GetRouteData方法的具体用法?C# HttpRequestMessage.GetRouteData怎么用?C# HttpRequestMessage.GetRouteData使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Http.HttpRequestMessage
的用法示例。
在下文中一共展示了HttpRequestMessage.GetRouteData方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetPerRequestFormatterInstance
public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request,MediaTypeHeaderValue mediaType)
{
//所需的对象属性
var includingFields = request.GetRouteData().Values["fields"];
if (includingFields != null && !string.IsNullOrEmpty(includingFields.ToString()))
{
FieldsJsonMediaTypeFormatter frmtr = new FieldsJsonMediaTypeFormatter();
frmtr.CurrentRequest = request;
var resolve = new Share.IncludableSerializerContractResolver(this.SerializerSettings.ContractResolver as Share.IgnorableSerializerContractResolver);
//type.IsAssignableFrom(typeof(IEnumerable<Model.dr_pre_visit>))
if (type.GetInterface("IEnumerable") != null)
{
resolve.Include(type.GenericTypeArguments[0], includingFields.ToString(), ',');
}
else
{
resolve.Include(type, includingFields.ToString(), ",");
}
frmtr.SerializerSettings = new JsonSerializerSettings
{
ContractResolver = resolve,
};
return frmtr;
}
else
{
return this;
}
}
示例2: SendAsync
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var resource = ((string)request.GetRouteData().Values["controller"]).ToLower();
var action = request.GetRouteData().Values.ContainsKey("action") ? ((string)request.GetRouteData().Values["action"]).ToLower() : null;
var method = request.Method.ToString().ToUpper();
var securityToken = GetToken(request);
try
{
_authenticationService.ValidateAccess(securityToken, resource, action, method);
}
catch (UnauthorizedException ex)
{
return request.CreateErrorResponse(HttpStatusCode.Unauthorized, ex.Message);
}
SaveContext(request, _authenticationService);
var response = await base.SendAsync(request, cancellationToken);
UpdateContext(request, _authenticationService);
securityToken = _authenticationService.CreateToken();
if (securityToken != null)
AddTokenToHeader(response, securityToken);
return response;
}
示例3: SendAsync
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var setting = Its.Configuration.Settings.Get<Config.SwaggerToolSettings>();
//using refletions to internal
var swaggerProvider = (ISwaggerProvider)_config.GetType().GetMethod("GetSwaggerProvider", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).Invoke(_config, new object[] { request });
var rootUrl = (string)_config.GetType().GetMethod("GetRootUrl", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).Invoke(_config, new object[] { request });
var q = request.GetRouteData().Values["q"].ToString();
var apiVersion = request.GetRouteData().Values["apiVersion"].ToString();
try
{
var swaggerDoc = swaggerProvider.GetSwagger(rootUrl, apiVersion);
//筛选条件为path包含q
IList<string> keytoremove = new List<string>();
foreach (var item in swaggerDoc.paths)
{
if (!item.Key.ToUpper().Contains(q.ToUpper()))
{
keytoremove.Add(item.Key);
}
}
foreach (var item in keytoremove)
{
swaggerDoc.paths.Remove(item);
}
var content = ContentFor(request, swaggerDoc);
return TaskFor(new HttpResponseMessage { Content = content });
}
catch (UnknownApiVersion ex)
{
return TaskFor(request.CreateErrorResponse(HttpStatusCode.NotFound, ex));
}
}
示例4: 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;
}
示例5: SelectController
public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
{
var controllers = GetControllerMapping();
var routeData = request.GetRouteData();
var controllerName = routeData.Values["controller"].ToString();
HttpControllerDescriptor descriptor;
if (controllers.TryGetValue(controllerName, out descriptor))
{
//var version = "2";
//var version = GetVersionFromQueryString(request);
//var version = GetVersionFromHeader(request);
//var version = GetVersionFromAcceptHeaderVersion(request);
var version = GetVersionFromMediaType(request);
var newName = string.Concat(controllerName, "V", version);
HttpControllerDescriptor versionedDescriptor;
if (controllers.TryGetValue(newName, out versionedDescriptor))
{
return versionedDescriptor;
}
return descriptor;
}
return null;
//return base.SelectController(request);
}
示例6: GetLinkedRoutePatterns
/// <summary>
/// This method must be set to LinkedRoutePatternProvider of CachingHandler
/// </summary>
/// <param name="message"></param>
/// <returns>All linked route patterns</returns>
public virtual IEnumerable<string> GetLinkedRoutePatterns(HttpRequestMessage request)
{
var routeData = request.GetRouteData();
if (routeData == null)
return new string[0];
var routeInfo = new RouteInfo(routeData.Route);
// deal with no parameters
if (routeInfo.Parameters.Count == 0)
return new string[0];
// deal with catchall
if (routeInfo.Parameters.Any(x => x.IsCatchAll))
return new string[0];
var linkedRoutePatterns = new List<string>();
linkedRoutePatterns.Add(routeInfo.GetRoot(routeData));
if (!routeInfo.IsCollection(routeData))
{
linkedRoutePatterns.Add(routeInfo.BuildCollectionPattern(routeData));
}
return linkedRoutePatterns;
}
示例7: GenerateLinksForTopic
private static Topic GenerateLinksForTopic(Topic topic, HttpRequestMessage request)
{
var routeData = request.GetRouteData();
var controller = routeData.Values["controller"];
var urlHelper = request.GetUrlHelper();
topic.SelfLink = new Uri(urlHelper.Route("DefaultApi", new { controller = controller, id = topic.Id }), UriKind.Relative);
if (topic.Comments != null && topic.Comments.Count > 0)
{
topic.Comments = new List<Comment>(topic.Comments.Select((cmt) =>
{
cmt.SelfLink = new Uri(urlHelper.Route("DefaultApi", new { controller = controller, id = cmt.Id }), UriKind.Relative);
cmt.TopicLink = new Uri(urlHelper.Route("DefaultApi", new { controller = "topics", id = cmt.TopicId }), UriKind.Relative);
return cmt;
}));
}
if (topic.Tags != null && topic.Tags.Count > 0)
{
topic.Tags = new List<Tag>(topic.Tags.Select((tag) =>
{
tag.SelfLink = new Uri(urlHelper.Route("DefaultApi", new { controller = controller, tags = tag.Name }), UriKind.Relative);
return tag;
}));
}
return topic;
}
示例8: SelectController
public HttpControllerDescriptor SelectController(HttpRequestMessage request)
{
if (request == null)
{
throw Error.ArgumentNull("request");
}
IHttpRouteData routeData = request.GetRouteData();
if (routeData == null)
{
return _innerSelector.SelectController(request);
}
ODataPath odataPath = request.GetODataPath();
if (odataPath == null)
{
return _innerSelector.SelectController(request);
}
foreach (IODataRoutingConvention routingConvention in _routingConventions)
{
string controllerName = routingConvention.SelectController(odataPath, request);
if (controllerName != null)
{
routeData.Values.Add(ODataRouteConstants.Controller, controllerName);
return _innerSelector.SelectController(request);
}
}
throw new HttpResponseException(request.CreateErrorResponse(
HttpStatusCode.NotFound,
Error.Format(SRResources.NoMatchingResource, request.RequestUri),
Error.Format(SRResources.NoRoutingHandlerToSelectController, odataPath.PathTemplate)));
}
示例9: GetControllerFullName
public IEnumerable<string> GetControllerFullName(HttpRequestMessage request, string controllerName)
{
object namespaceName;
var data = request.GetRouteData();
IEnumerable<string> keys = _apiControllerCache.Value.ToDictionary<KeyValuePair<string, Type>, string, Type>(t => t.Key,
t => t.Value, StringComparer.CurrentCultureIgnoreCase).Keys.ToList();
if (data.Route.DataTokens == null ||
!data.Route.DataTokens.TryGetValue(NamespaceRouteVariableName, out namespaceName))
{
return from k in keys
where k.EndsWith(string.Format(".{0}{1}", controllerName, DefaultHttpControllerSelector.ControllerSuffix), StringComparison.CurrentCultureIgnoreCase)
select k;
}
//get the defined namespace
string[] namespaces = (string[])namespaceName;
return from n in namespaces
join k in keys on string.Format("{0}.{1}{2}", n, controllerName, DefaultHttpControllerSelector.ControllerSuffix).ToLower() equals k.ToLower()
select k;
}
示例10: GetControllerIdentificationFromRequest
protected override ControllerIdentification GetControllerIdentificationFromRequest(HttpRequestMessage request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
IHttpRouteData routeData = request.GetRouteData();
if (routeData == null)
{
return default(ControllerIdentification);
}
// Look up controller in route data
string controllerName = this.GetControllerNameFromRequest(request);
// Also try the version if possible
object apiVersionObj;
string apiVersion = null;
//string version;
//if (routeData.Values.TryGetValue(VersionKey, out apiVersionObj) &&
// Int32.TryParse(apiVersionObj.ToString(), out version))
//{
// apiVersion = version;
//}
if (routeData.Values.TryGetValue(VersionKey, out apiVersionObj) && !string.IsNullOrWhiteSpace(apiVersionObj.ToString()))
{
apiVersion = apiVersionObj.ToString().Replace(".", "_");
}
return new ControllerIdentification(controllerName, apiVersion);
}
示例11: SendAsync
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
StringBuilder sb = new StringBuilder("/");
if (!string.IsNullOrEmpty(subdir))
{
sb.AppendFormat("{0}/", subdir);
}
sb.Append("Default.cshtml");
var routeData = request.GetRouteData();
if (routeData != null && routeData.Values.Count > 0)
{
sb.Append("?");
foreach (var r in routeData.Values)
{
sb.AppendFormat("{0}={1}&", r.Key, r.Value);
}
sb.Remove(sb.Length - 1, 1);
}
var url = request.RequestUri.AbsoluteUri;
url = url.Replace(request.RequestUri.AbsolutePath, sb.ToString());
request.RequestUri = new Uri(url);
if (request.Method == HttpMethod.Get || request.Method == HttpMethod.Options)
request.Content = null;
return base.SendAsync(request, cancellationToken);
}
示例12: SendAsync
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Method == HttpMethod.Options)
{
var apiExplorer = request.GetConfiguration().Services.GetApiExplorer();
var controllerRequested = request.GetRouteData().Values["controller"] as string;
var supportedMethods = apiExplorer.ApiDescriptions
.Where(d =>
{
var controller = d.ActionDescriptor.ControllerDescriptor.ControllerName;
return string.Equals(
controller, controllerRequested, StringComparison.OrdinalIgnoreCase);
})
.Select(d => d.HttpMethod.Method)
.Distinct();
if (!supportedMethods.Any())
{
return Task.FromResult(request.CreateResponse(HttpStatusCode.NotFound));
}
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.Add("Access-Control-Allow-Origin", "*");
response.Headers.Add("Access-Control-Allow-Methods", string.Join(",", supportedMethods));
return Task.FromResult(response);
}
return base.SendAsync(request, cancellationToken);
}
示例13: 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);
}
示例14: SendAsync
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
IHttpRouteData routeData = request.GetRouteData();
int key;
if(!int.TryParse(routeData.Values["customerkey"].ToString(), out key)) {
return Task.FromResult(
request.CreateResponse(HttpStatusCode.NotFound)
);
}
var dependecyScope = request.GetDependencyScope();
var customerRepo = (IEntityRepository<Customer>)dependecyScope.GetService(typeof(IEntityRepository<Customer>));
var customer = customerRepo.GetSingle(key);
if (customer == null) {
return Task.FromResult(
request.CreateResponse(HttpStatusCode.NotFound)
);
}
return base.SendAsync(request, cancellationToken);
}
示例15: SelectController
//[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Caller is responsible for disposing of response instance.")]
public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
{
//if (request == null)
//{
// throw Error.ArgumentNull("request");
//}
//request.
var version = GetVersionFromMediaType(request);
IHttpRouteData routeData = request.GetRouteData();
var a = routeData.GetDirectRouteCandidates();
HttpControllerDescriptor controllerDescriptor;
if (routeData != null)
{
controllerDescriptor = GetVersionedRouteController(routeData, version);
if (controllerDescriptor != null)
{
return controllerDescriptor;
}
}
// var routeTemplate = routeData.Route.RouteTemplate;
return null;
}
开发者ID:Microshaoft,项目名称:Microshaoft.Common.Utilities.Net.4x,代码行数:30,代码来源:WebApiVersionedControllerSelector.cs