Ejemplo n.º 1
0
        public static void Register(HttpConfiguration config)
        {
            var bson = new BsonMediaTypeFormatter();

            config.Formatters.Add(bson);
            var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            jsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto;
            //jsonFormatter.SerializerSettings.Converters.Add(new JsonNetBsonDocumentConverter());

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new {id = RouteParameter.Optional}
                );
        }
Ejemplo n.º 2
0
        /// <summary>
        /// http://www.asp.net/web-api/overview/formats-and-model-binding/bson-support-in-web-api-21
        /// </summary>
        public async Task Transmit(Image<Bgr, byte> image)
        {
            if (!_enabled)
            {
                return;
            }

            if (_transmitting)
            {
                return;
            }

            _transmitting = true;
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(RootUrl);

                // Set the Accept header for BSON.
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));
                
                // POST using the BSON formatter.
                MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
                try
                {
                    var result = await client.PostAsync(UrlRoute, GetPostBody(image), bsonFormatter);
                    result.EnsureSuccessStatusCode();
                }
                catch (Exception httpEx)
                {
                    const int retryMilliseconds = 20000;
                    Console.WriteLine($"BsonPost: {httpEx}. Retrying in {retryMilliseconds}");
                    _enabled = false;
                    _retryTimer = new Timer(retryMilliseconds);
                    _retryTimer.Elapsed += (sender, args) => _enabled = true;
                    _retryTimer.Start();
                }
                finally
                {
                    _transmitting = false;
                }
            }
        }
Ejemplo n.º 3
0
        // This code configures Web API. The Startup class is specified as a type
        // parameter in the WebApp.Start method.
        public void Configuration(IAppBuilder appBuilder)
        {

            // Configure Web API for self-host. 
            HttpConfiguration config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            // 默认返回Json数据
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

            var bson = new BsonMediaTypeFormatter();
            bson.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/bson"));
            config.Formatters.Add(bson);

            appBuilder.UseWebApi(config);
        }
Ejemplo n.º 4
0
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            // Configure Json.Net serializer to use camel case property names
            config.Formatters.JsonFormatter.SerializerSettings
                .ContractResolver = new CamelCasePropertyNamesContractResolver();

            // Configure Json.Net to handle cyclical references
            //config.Formatters.JsonFormatter.SerializerSettings
            //    .PreserveReferencesHandling = PreserveReferencesHandling.All;

            // Configure the Xml formatter serializer to handle cyclical references
            // - Add a reference to System.Runtime.Serialization
            //var dcs = new DataContractSerializer(typeof(Person), null, int.MaxValue,
            //    false, /* preserveObjectReferences */ true, null);
            //config.Formatters.XmlFormatter.SetSerializer<Person>(dcs);

            // Configure both json and xml to handle cycles
            // - Install the AspNetWebApi2Helpers.Serialization package
            config.Formatters.JsonPreserveReferences();
            config.Formatters.XmlPreserveReferences();

            // Add Bson media type formatter
            var bson = new BsonMediaTypeFormatter();
            bson.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.All;
            config.Formatters.Add(bson);

            // Add Protobuf formatter
            // - Add [ProtoContract] and [ProtoMember] attributes to Person class
            config.Formatters.Add(new ProtoBufFormatter());

            app.UseWebApi(config);
            app.UseWelcomePage();
        }
        public static void RegisterDbWebApi(this HttpConfiguration config, bool supportRazor = true, bool supportJsonp = true, bool supportXlsx = true, bool supportCsv = true, bool supportBson = true)
        {
            DbWebApiOptions.DerivedParametersCacheExpireInterval = TimeSpan.FromMinutes(15);

            #if WEB_API2
            if (supportBson)
            {
                BsonMediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
                bsonFormatter.AddMediaTypeMapping("bson", BsonMediaTypeFormatter.DefaultMediaType, null);
                config.Formatters.Add(bsonFormatter);
            }
            #endif
            if (supportCsv)
                config.AddFormatPlug(new CsvFormatPlug());
            if (supportXlsx)
                config.AddFormatPlug(new XlsxFormatPlug());
            if (supportJsonp)
                config.Formatters.Add(new JsonpMediaTypeFormatter());
            if (supportRazor)
                config.Formatters.Add(new RazorMediaTypeFormatter());
        }
Ejemplo n.º 6
0
        public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务
            // 将 Web API 配置为仅使用不记名令牌身份验证。
            //config.SuppressDefaultHostAuthentication();
            //config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // 默认返回Json数据
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

            var bson = new BsonMediaTypeFormatter();
            bson.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/bson"));
            config.Formatters.Add(bson);

            // Web API 路由
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="BsonMediaTypeFormatter"/> class.
 /// </summary>
 /// <param name="formatter">The <see cref="BsonMediaTypeFormatter"/> instance to copy settings from.</param>
 protected BsonMediaTypeFormatter(BsonMediaTypeFormatter formatter)
     : base(formatter)
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="BsonMediaTypeFormatter"/> class.
 /// </summary>
 /// <param name="formatter">The <see cref="BsonMediaTypeFormatter"/> instance to copy settings from.</param>
 protected BsonMediaTypeFormatter(BsonMediaTypeFormatter formatter)
     : base(formatter)
 {
 }
Ejemplo n.º 9
0
        public static void Register(HttpConfiguration config)
        {
            //// Uncomment the following to use the documentation from XML documentation file.
            //config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));

            //// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type.
            //// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type 
            //// formats by the available formatters.
            //config.SetSampleObjects(new Dictionary<Type, object>
            //{
            //    {typeof(string), "sample string"},
            //    {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}}
            //});

            // Extend the following to provide factories for types not handled automatically (those lacking parameterless
            // constructors) or for which you prefer to use non-default property values. Line below provides a fallback
            // since automatic handling will fail and GeneratePageResult handles only a single type.
#if Handle_PageResultOfT
            config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult);
#endif

            // Extend the following to use a preset object directly as the sample for all actions that support a media
            // type, regardless of the body parameter or return type. The lines below avoid display of binary content.
            // The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object.
            var bsonFormatter = new BsonMediaTypeFormatter();
            byte[] bson;
            using (var s = new MemoryStream())
            {
                bsonFormatter.WriteToStream(typeof(string), "Hello world", s, Encoding.UTF8);
                bson = s.ToArray();
            }
            config.SetSampleForMediaType(
                new ByteSample { Bytes = bson },
                new MediaTypeHeaderValue("application/bson"));


            var rss = @"<?xml version=""1.0"" encoding=""UTF-8"" ?>
                <rss version=""2.0"">
                <channel>
                 <title>Title</title>
                 <description>Desc</description>
                 <link>http://www.test.com</link>
                 <pubDate>Tue, 21 Jan 2014 18:45:00 +0000 </pubDate>
 
                 <item>
                  <title>Item</title>
                  <description>Desc</description>
                  <link>http://www.test.com/1</link>
                 <pubDate>Tue, 21 Jan 2014 18:45:00 +0000 </pubDate>
                 </item>
 
                </channel>
                </rss>";
            config.SetSampleResponse(rss, new MediaTypeHeaderValue("text/rss"), "Values", "Get");

            //// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format
            //// and have IEnumerable<string> as the body parameter or return type.
            //config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>));

            //// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values"
            //// and action named "Put".
            //config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put");

            //// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png"
            //// on the controller named "Values" and action named "Get" with parameter "id".
            //config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id");

            //// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>.
            //// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter.
            //config.SetActualRequestType(typeof(string), "Values", "Get");

            //// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>.
            //// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string.
            //config.SetActualResponseType(typeof(string), "Values", "Post");
        }
Ejemplo n.º 10
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "SecureApi",
                routeTemplate: "api/values",
                constraints: null,
                handler: new HmacAuthenticationHandler(new ApiKeyRepository(),
                    new CanonicalRepresentationBuilder(), new HmacSignatureCalculator())
                {
                    InnerHandler = new HttpControllerDispatcher(config)
                },
                defaults: new { controller = "values" }
            );

            config.Routes.MapHttpRoute(
                name: "SecureImportApi",
                routeTemplate: "api/hmacimportdata",
                constraints: null,
                handler: new HmacAuthenticationHandler(new ApiKeyRepository(),
                    new CanonicalRepresentationBuilder(), new HmacSignatureCalculator())
                {
                    InnerHandler = new HttpControllerDispatcher(config)
                },
                defaults: new { controller = "hmacimportdata" }
            );


            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            /*
             * 
             * MIME TYPES AND CONTENT NEGOTATION STUFF
             * Should move this to a different method, but since it's a sample app.... well, yaknow...
             * 
             */

            //Drop XML as a content type since forward compatibility with it is a pain in the butt thanks to XML schemas
            var applicationXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes
               .FirstOrDefault(p => p.MediaType == "application/xml");
            config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(applicationXmlType);

            var xmlFormatter = config.Formatters.XmlFormatter;
            config.Formatters.Remove(xmlFormatter);

            //Set JSON output to camelCase identifiers to conform with standard JS conventions
            var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().FirstOrDefault();
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            CreateJsonMediaTypes(jsonFormatter);

            //BSON is supported in WebAPI v2.1+
            var bsonFormatter = new BsonMediaTypeFormatter();
            config.Formatters.Add(bsonFormatter);

            //Binary JSON serialisation - added in v2 of the API
            //Why? Maybe we wanted to include an embedded jpeg of the contact in the response 
            //so there are less server requests.
            bsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.sampleOrg.contact+bson"));
            bsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.sampleOrg.contact.v2+bson"));

            //Custom code to configure which controller is called
            config.Services.Replace(typeof(IHttpControllerSelector), new ApiVersioningSelector(config));

            config.MessageHandlers.Add(new NotAcceptableContentNegotiationHandler(config));

            config.Filters.Add(new CustomApiExceptionAttribute());
        }
        static async Task RunAsync()
        {
            MediaTypeFormatter formatter = new BsonMediaTypeFormatter();
            MediaTypeFormatter[] formatters = new MediaTypeFormatter[] { formatter, };

            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = _baseAddress;

                // All responses in BSON format
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));

                // POST api/MyData to create api/MyData/1 (send and receive MyData)
                MyData data = new MyData
                {
                    Name = "First",
                    Decimal = -90998887666m,
                    Double = 37.777777777777777777d,
                    Long = 238470192387401239L,
                    TimeSpan = TimeSpan.Zero,
                };
                Uri[] uris = new Uri[2];

                Console.WriteLine("POSTing to '/api/MyData'");
                HttpResponseMessage response = await client.PostAsync<MyData>("api/MyData", data, formatter);
                response.EnsureSuccessStatusCode();
                uris[0] = response.Headers.Location;
                Console.WriteLine("  ... success; created resource at '{0}'", uris[0].PathAndQuery);
                Console.WriteLine("  ... response was {0} bytes", response.Content.Headers.ContentLength);

                // Unused but could confirm returned data is unchanged (MyDataController makes no changes on POST)
                data = await response.Content.ReadAsAsync<MyData>(formatters);

                // POST api/MyData to create api/MyData/2
                data = new MyData
                {
                    Name = "Second",
                    Decimal = 999999999999m,
                    Double = 3.3498712034e37d,
                    Long = -91348701321872304L,
                    TimeSpan = new TimeSpan(0, 12, 13, 14, 123),
                };

                Console.WriteLine("POSTing to '/api/MyData'");
                response = await client.PostAsync<MyData>("api/MyData", data, formatter);
                response.EnsureSuccessStatusCode();
                uris[1] = response.Headers.Location;
                Console.WriteLine("  ... success; created resource at '{0}'", uris[1].PathAndQuery);

                // GET api/MyData (receive enumeration of MyData)
                Console.WriteLine("GETting from '/api/MyData'");
                response = await client.GetAsync("api/MyData");
                response.EnsureSuccessStatusCode();
                Console.WriteLine("  ... success; response was {0} bytes", response.Content.Headers.ContentLength);

                MyData[] allData = await response.Content.ReadAsAsync<MyData[]>(formatters);
                foreach (MyData returned in allData)
                {
                    PrettyPrint("  ...", returned);
                }

                // DELETE api/MyData/x (receive MyData)
                foreach (Uri uri in uris)
                {
                    Console.WriteLine("DELETing resource at '{0}'", uri.PathAndQuery);
                    response = await client.DeleteAsync(uri);
                    response.EnsureSuccessStatusCode();

                    data = await response.Content.ReadAsAsync<MyData>(formatters);
                    PrettyPrint("  ... success;", data);
                }
            }
        }