public static class HttpRequestMessageExtensions { /// <summary> /// Gets the <see cref="HttpConfiguration"/> for the given request. /// </summary> /// <param name="request">The HTTP request.</param> /// <returns>The <see cref="HttpConfiguration"/>.</returns> public static HttpConfiguration GetConfiguration(this HttpRequestMessage request) { if (request == null) { throw new ArgumentException("request"); } return request.GetProperty<HttpConfiguration>(HttpPropertyKeys.HttpConfigurationKey); } /// <summary> /// Gets the <see cref="System.Threading.SynchronizationContext"/> for the given request or null if not available. /// </summary> /// <param name="request">The HTTP request.</param> /// <returns>The <see cref="System.Threading.SynchronizationContext"/> or null.</returns> public static SynchronizationContext GetSynchronizationContext(this HttpRequestMessage request) { if (request == null) { throw new ArgumentException("request"); } return request.GetProperty<SynchronizationContext>(HttpPropertyKeys.SynchronizationContextKey); } /// <summary> /// Gets the <see cref="System.Web.Http.Routing.IHttpRouteData"/> for the given request or null if not available. /// </summary> /// <param name="request">The HTTP request.</param> /// <returns>The <see cref="System.Web.Http.Routing.IHttpRouteData"/> or null.</returns> public static IHttpRouteData GetRouteData(this HttpRequestMessage request) { if (request == null) { throw new ArgumentException("request"); } return request.GetProperty<IHttpRouteData>(HttpPropertyKeys.HttpRouteDataKey); } public static T GetProperty<T>(this HttpRequestMessage request, string key) { T value = default(T); object @object = null; request.Properties.TryGetValue(key, out @object); if (@object is T) { value = (T)@object; } else { throw new InvalidCastException(string.Format("无效类型转换:{0}", typeof(T).FullName)); } return value; } }