예제 #1
1
        public static void Register(HttpConfiguration config)
        {
            var cors = new EnableCorsAttribute("*", "*", "GET, POST, PUT, DELETE, OPTIONS", "Signature");
            config.EnableCors();

            // Web API 配置和服务
            config.Formatters.Clear();
            var jsonFormatter = new JsonMediaTypeFormatter();
            // Convert all dates to UTC type
            jsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
            // Convert all dates to Microsoft type("\/Date(ticks)\/ ")
            //jsonFormatter.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
            jsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
            jsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All;
            jsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            config.Formatters.Add(jsonFormatter);
            //config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));

            // Web API 路由
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
        // GET api/values/5
        public HttpResponseMessage Get(int? id)
        {
            if (id == null)
                throw new HttpResponseException(HttpStatusCode.NotFound);

            var result = new User
                {
                    Age = 34,
                    Birthdate = DateTime.Now,
                    ConvertedUsingAttribute = DateTime.Now,
                    Firstname = "Ugo",
                    Lastname = "Lattanzi",
                    IgnoreProperty = "This text should not appear in the reponse",
                    Salary = 1000,
                    Username = "******",
                    Website = new Uri("http://www.tostring.it")
                };

            var formatter = new JsonMediaTypeFormatter();
            var json = formatter.SerializerSettings;

            json.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat;
            json.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
            json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
            json.Formatting = Newtonsoft.Json.Formatting.Indented;
            json.ContractResolver = new CamelCasePropertyNamesContractResolver();
            json.Culture = new CultureInfo("en-US");

            return Request.CreateResponse(HttpStatusCode.OK, result, formatter);
        }
 public static void UseJsonOnly(this HttpConfiguration config)
 {
     var jsonFormatter = new JsonMediaTypeFormatter();
     config.Services.Replace(typeof(IContentNegotiator), new JsonOnlyContentNegotiator(jsonFormatter));
     config.Formatters.Clear();
     config.Formatters.Add(jsonFormatter);
 }
예제 #4
0
파일: WebHelper.cs 프로젝트: yuanfei05/vita
    public static void ConfigureWebApi(HttpConfiguration httpConfiguration, EntityApp app, 
                             LogLevel logLevel = LogLevel.Basic,
                             WebHandlerOptions webHandlerOptions = WebHandlerOptions.DefaultDebug) {
      // Logging message handler
      var webHandlerStt = new WebCallContextHandlerSettings(logLevel, webHandlerOptions);
      var webContextHandler = new WebCallContextHandler(app, webHandlerStt);
      httpConfiguration.MessageHandlers.Add(webContextHandler);

      // Exception handling filter - to handle/save exceptions
      httpConfiguration.Filters.Add(new ExceptionHandlingFilter());

      // Formatters - add formatters with spies, to catch/log deserialization failures
      httpConfiguration.Formatters.Clear();
      httpConfiguration.Formatters.Add(new StreamMediaTypeFormatter("image/jpeg", "image/webp")); //webp is for Chrome
      var xmlFmter = new XmlMediaTypeFormatter();
      httpConfiguration.Formatters.Add(xmlFmter);
      var jsonFmter = new JsonMediaTypeFormatter();
      // add converter that will serialize all enums as strings, not integers
      jsonFmter.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
      var resolver = jsonFmter.SerializerSettings.ContractResolver = new JsonContractResolver(jsonFmter);
      httpConfiguration.Formatters.Add(jsonFmter);

      //Api configuration
      if (app.ApiConfiguration.ControllerInfos.Count > 0)
        ConfigureSlimApi(httpConfiguration, app);
    }
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();

            var container = ConfigureAutoFac.ConfigureMvc();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            //Dit op Configure laten staan, dit wordt namelijk niet in web requests gebruikt
            // Remove the old formatter, add the new one.
            var formatter = new JsonMediaTypeFormatter();
            formatter.SerializerSettings = new JsonSerializerSettings
            {
                Formatting = Formatting.Indented,
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            };

            config.Formatters.Remove(config.Formatters.JsonFormatter);
            config.Formatters.Add(formatter);
            config.Formatters.Remove(config.Formatters.XmlFormatter);
            WebApiConfig.Register(config);

            app.UseCors(CorsOptions.AllowAll);
            app.UseAutofacMiddleware(container);
            app.UseAutofacMvc();
            app.UseAutofacWebApi(config);
            app.UseWebApi(config);
            ConfigureAuth(app);
        }
예제 #6
0
        public void TestMethod1()
        {
            try
            {
                Task serviceTask = new Task();
                serviceTask.TaskId = 1;
                serviceTask.Subject = "Test Task";
                serviceTask.StartDate = DateTime.Now;
                serviceTask.DueDate = null;
                serviceTask.CompletedDate = DateTime.Now;
                serviceTask.Status = new Status
                {
                    StatusId = 3,
                    Name = "Completed",
                    Ordinal = 2
                };
                serviceTask.Links = new System.Collections.Generic.List<Link>();
                serviceTask.Assignees = new System.Collections.Generic.List<User>();
                

                serviceTask.SetShouldSerializeAssignees(true);

                var formatter = new JsonMediaTypeFormatter();

                var content = new ObjectContent<Task>(serviceTask, formatter);
                var reuslt = content.ReadAsStringAsync().Result;

            }
            catch(Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
        /// <summary>
        /// Helper method to create ErrorRespone
        /// </summary>
        /// <param name="request">This should be the source request. For Eg: </param>
        /// <param name="body"></param>
        /// <returns></returns>
        public static HttpResponseMessage CreateErrorResponse(HttpRequestMessage request, ErrorResponseBody body)
        {
            var jsonFormatter = new JsonMediaTypeFormatter();
            jsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;

            return request.CreateResponse<ErrorResponseBody>(body.Status, body, jsonFormatter);
        }
예제 #8
0
        public static void Register(HttpConfiguration config)
        {
            try
            {
                // Find assembly from path defined in web.config
                var path = PayAtTable.API.Properties.Settings.Default.DataRepositoryAssembly;
                var mappedPath = System.Web.Hosting.HostingEnvironment.MapPath(path);
                Assembly assembly = Assembly.LoadFrom(mappedPath);

                // Register data repository implementations with the IoC container
                var container = TinyIoCContainer.Current;
                container.Register(typeof(IOrdersRepository), LoadInstanceFromAssembly(typeof(IOrdersRepository), assembly)).AsPerRequestSingleton();
                container.Register(typeof(ITablesRepository), LoadInstanceFromAssembly(typeof(ITablesRepository), assembly)).AsPerRequestSingleton();
                container.Register(typeof(IEFTPOSRepository), LoadInstanceFromAssembly(typeof(IEFTPOSRepository), assembly)).AsPerRequestSingleton();
                container.Register(typeof(ITendersRepository), LoadInstanceFromAssembly(typeof(ITendersRepository), assembly)).AsPerRequestSingleton();
                container.Register(typeof(ISettingsRepository), LoadInstanceFromAssembly(typeof(ISettingsRepository), assembly)).AsPerRequestSingleton();

                // Uncomment the following code to load a local data repository in this project rather than an external DLL
                //container.Register<IOrdersRepository, DemoRepository>().AsPerRequestSingleton();
                //container.Register<ITablesRepository, DemoRepository>().AsPerRequestSingleton();
                //container.Register<IEFTPOSRepository, DemoRepository>().AsPerRequestSingleton();
                //container.Register<ITendersRepository, DemoRepository>().AsPerRequestSingleton();
                //container.Register<ISettingsRepository, DemoRepository>().AsPerRequestSingleton();

                // Set Web API dependancy resolver
                System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new TinyIocWebApiDependencyResolver(container);

                // Uncomment the following code to support XML
                //var xmlMediaTypeFormatter = new XmlMediaTypeFormatter();
                //xmlMediaTypeFormatter.AddQueryStringMapping("format", "xml", "text/xml");
                //config.Formatters.Add(xmlMediaTypeFormatter);

                // Add JSON formatter
                var jsonMediaTypeFormatter = new JsonMediaTypeFormatter() { SerializerSettings = new Newtonsoft.Json.JsonSerializerSettings() { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore } };
                jsonMediaTypeFormatter.AddQueryStringMapping("format", "json", "application/json");
                config.Formatters.Add(jsonMediaTypeFormatter);

                var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
                json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;

                // Web API2 routes
                config.MapHttpAttributeRoutes();

                // Uncomment the following code to support WEB API v1 routing
                //config.Routes.MapHttpRoute(
                //    name: "DefaultApi",
                //    routeTemplate: "api/{controller}/{id}",
                //    defaults: new { id = RouteParameter.Optional }
                //);

                // Uncomment the following to add a key validator to the message pipeline.
                // This will check that the "apikey" parameter in each request matches an api key in our list.
                config.MessageHandlers.Add(new ApiKeyHandler("key"));
            }
            catch (Exception ex)
            {
                log.ErrorEx((tr) => { tr.Message = "Exception encounted during configuration"; tr.Exception = ex; });
                throw ex;
            }
        }
예제 #9
0
        public HttpResponseMessage Get()
        {
            try
            {
                var formatter = new JsonMediaTypeFormatter();
                var json = formatter.SerializerSettings;
                json.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
                json.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
                json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
                json.Formatting = Newtonsoft.Json.Formatting.Indented;
                json.ContractResolver = new CamelCasePropertyNamesContractResolver();

                var lang = _bhtaEntities.Languages.ToList()
                    .Select(m => new LanguageModel()
                    {
                        Id = m.Id,
                        CategoryId = m.CategoryId,
                        Description = m.Description,
                        Category = new CategoryModel() { Id = m.Category.Id, Name = m.Category.Name, Description = m.Category.Description, Permalink = m.Category.Permalink },
                        Image = string.IsNullOrEmpty(m.Image) ? null : ValueConfig.LinkImage + m.Image,
                        KeyLanguage = m.KeyLanguage,
                        Sound = string.IsNullOrEmpty(m.Sound) ? null : ValueConfig.LinkSound + m.Sound,
                        ValueLanguage = _js.Deserialize<LanguageName>(m.ValueLanguage)
                    });

                return Request.CreateResponse(HttpStatusCode.OK, lang, formatter);
            }
            catch (Exception exception)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exception.ToString());
            }
        }
예제 #10
0
        public static void Register(HttpConfiguration config)
        {
            config.Formatters.Clear();

            //config.Formatters.Add(new XmlMediaTypeFormatter());
            var formater = new JsonMediaTypeFormatter();
            //formater.SerializerSettings.Converters.Add(new DateTimeConverterHelper());
            formater.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
            config.Formatters.Add(formater);

            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));


            //Enable CORS for all origins, all headers, and all methods,
            var cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);

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



        }
        public Task<List<IdentityProviderInformation>> GetAsync(string protocol)
        {
            var url = string.Format(
                "https://{0}.{1}/v2/metadata/IdentityProviders.js?protocol={2}&realm={3}&context={4}&version=1.0",
                AcsNamespace,
                "accesscontrol.windows.net",
                protocol,
                Realm,
                Context);

            var jsonFormatter = new JsonMediaTypeFormatter();
            jsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/javascript"));

            var formatters = new List<MediaTypeFormatter>()
            {
                jsonFormatter
            };

            var client = new HttpClient();

            var t1 = client.GetAsync(new Uri(url));
            var t2 = t1.ContinueWith(
                innerTask =>
                {
            		return t1.Result.Content.ReadAsAsync<List<IdentityProviderInformation>>(formatters);
                });
            var t3 = t2.ContinueWith<List<IdentityProviderInformation>>(
                innerTask =>
                {
                    return t2.Result.Result;
                });
            return t3;
        }
예제 #12
0
파일: WebApiConfig.cs 프로젝트: bouwe77/fmg
        public static void Register(HttpConfiguration config)
        {
            // HAL content negotiation.
             var jsonFormatter = new JsonMediaTypeFormatter
             {
            // JSON settings: Do not show empty fields and camelCase field names.
            SerializerSettings =
            {
               NullValueHandling = NullValueHandling.Ignore,
               ContractResolver = new CamelCasePropertyNamesContractResolver()
            }
             };
             config.Services.Replace(typeof(IContentNegotiator), new HalContentNegotiator(jsonFormatter));

             // Catch and log all unhandled exceptions.
             config.Services.Add(typeof(IExceptionLogger), new MyExceptionLogger());

             // Do not include error details (e.g. stacktrace) in responses.
             config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Never;

             // Web API routes
             config.MapHttpAttributeRoutes();

             // Default routes werkt niet, dus ik ga alle routes wel met de hand in RouteConfig.cs zetten...
             //config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional });

             GlobalConfiguration.Configuration.Filters.Add(new BasicAuthenticationFilter(active: true));
        }
예제 #13
0
        private static void ConfigureDefaults(HttpConfiguration config)
        {
            //config.Filters.Add(new ExceptionActionFilter());
            //config.Filters.Add(new ValidationActionFilter());
            //Delete all formatter and add only JSON formatting for request and response
            config.Formatters.Clear();
            var formatter = new JsonMediaTypeFormatter()
            {
                SerializerSettings =
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver(),
                    DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
                    DateTimeZoneHandling = DateTimeZoneHandling.Utc
                },
            };
            config.Formatters.Add(formatter);

            try
            {
                var dbModelHolder = unityContainer.Resolve<DbModelHolder>();
                dbModelHolder.ConnectionString =
                    ConfigurationManager.ConnectionStrings["CommonDbContext"].ConnectionString;
            }
            catch (Exception e)
            {
                _logger.Error("dbModelHanlder Configuration failed", e);
            }
        }
 /// <summary>
 /// Gets the HTTP response message.
 /// </summary>
 /// <param name="message">The message.</param>
 /// <returns></returns>
 private HttpResponseMessage GetHttpResponseMessage(ApiBaseModel message)
 {
     var httpmessage = new HttpResponseMessage();
     var jsonmedia = new JsonMediaTypeFormatter();
     httpmessage.Content = new ObjectContent(typeof(ApiBaseModel), message, jsonmedia);
     return httpmessage;
 }
예제 #15
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();
            config.EnableCors();

            var formatter = new JsonMediaTypeFormatter();

            // Serialize and deserialize JSON as "myProperty" => "MyProperty" -> "myProperty"
            formatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            // Make JSON easier to read for debugging at the expense of larger payloads
            formatter.SerializerSettings.Formatting = Formatting.Indented;

            // Omit nulls to reduce payload size
            formatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;

            // Explicitly define behavior when serializing DateTime values
            formatter.SerializerSettings.DateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ssK";   // Only return DateTimes to a 1 second precision.
            formatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;       // Only return UTC for DateTimes values.

            // Only support JSON for REST API requests
            config.Formatters.Clear();
            config.Formatters.Add(formatter);

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
예제 #16
0
        public BasicUserData GetUser()
        {
            var builder = new UriBuilder(userInfoBaseUrl)
            {
                Query = string.Format("access_token={0}", Uri.EscapeDataString(accessToken))
            };

            var profileClient = new HttpClient();
            HttpResponseMessage profileResponse = profileClient.GetAsync(builder.Uri).Result;

            var formatter = new JsonMediaTypeFormatter();
            formatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/javascript"));
            var userInfo = profileResponse.Content.ReadAsAsync<JToken>(new[] { formatter }).Result;

            return
            new BasicUserData
            {
                UserId = userInfo.Value<string>("id"),
                UserName = userInfo.Value<string>("name"),
                FirstName = userInfo.Value<string>("given_name"),
                LastName = userInfo.Value<string>("family_name"),
                PictureUrl = userInfo.Value<string>("picture"),
                Email = userInfo.Value<string>("email")
            };
        }
예제 #17
0
        public bool IsTokenValid()
        {
            var tokenValidatorUrl = new UriBuilder(tokenValidatorBaseUrl)
            {
                Query = string.Format("access_token={0}", accessToken)
            };

            var client = new HttpClient();
            HttpResponseMessage validationResponse = client.GetAsync(tokenValidatorUrl.Uri).Result;

            var formatter = new JsonMediaTypeFormatter();
            formatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/javascript"));
            var responseData = validationResponse.Content.ReadAsAsync<JToken>(new[] { formatter }).Result;

            var error = responseData.Value<string>("error");
            var audience = responseData.Value<string>("audience");

            //if an error was returned, the token is invalid
            if (error != null)
            {
                return false;
            }
            //ensure the token is valid for THIS app
            else if (audience == null || audience != clientAppId)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
예제 #18
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

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

            var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
            config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);

            //force json only
            var jsonFormatter = new JsonMediaTypeFormatter
            {
                SerializerSettings =
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                }
            };
            //optional: set serializer settings here
            config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
            config.Formatters.Insert(0, new JsonNetFormatter());
        }
        /// <inheritdoc />
        public virtual void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)
        {
            if (controllerSettings == null)
            {
                throw new ArgumentNullException("controllerSettings");
            }

            JsonMediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
            JsonSerializerSettings serializerSettings = jsonFormatter.SerializerSettings;

            // Set up date/time format to be ISO 8601 but with 3 digits and "Z" as UTC time indicator. This format
            // is the JS-valid format accepted by most JS clients.
            IsoDateTimeConverter dateTimeConverter = new IsoDateTimeConverter()
            {
                Culture = CultureInfo.InvariantCulture,
                DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFZ",
                DateTimeStyles = DateTimeStyles.AdjustToUniversal
            };

            // Ignoring default values while serializing was affecting offline scenarios as client sdk looks at first object in a batch for the properties.
            // If first row in the server response did not include columns with default values, client sdk ignores these columns for the rest of the rows
            serializerSettings.DefaultValueHandling = DefaultValueHandling.Include;
            serializerSettings.NullValueHandling = NullValueHandling.Include;
            serializerSettings.Converters.Add(new StringEnumConverter());
            serializerSettings.Converters.Add(dateTimeConverter);
            serializerSettings.MissingMemberHandling = MissingMemberHandling.Error;
            serializerSettings.CheckAdditionalContent = true;
            serializerSettings.ContractResolver = new ServiceContractResolver(jsonFormatter);
            controllerSettings.Formatters.Remove(controllerSettings.Formatters.JsonFormatter);
            controllerSettings.Formatters.Insert(0, jsonFormatter);
        }
예제 #20
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

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

            config.Filters.Add(new GlobalExceptionFilterAttribute());

            var jsonformatter = new JsonMediaTypeFormatter
            {
                SerializerSettings = ApiJsonSerializerSettings
            };

            config.Formatters.RemoveAt(0);
            config.Formatters.Insert(0, jsonformatter);

            //config.Formatters.JsonFormatter.SerializerSettings = ApiJsonSerializerSettings;

            config.Formatters.JsonFormatter.SerializerSettings.Error = (object sender, ErrorEventArgs args) =>
            {

                //errors.Add(args.ErrorContext.Error.Message);
                args.ErrorContext.Handled = true;
            };
        }
예제 #21
0
		public static void Register(HttpConfiguration config) {

			//config.EnableCors();

			config.MapHttpAttributeRoutes();

			//config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

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

				//var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();

				config.Formatters.Clear();
				var jsonFormatter = new JsonMediaTypeFormatter();
				jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
				config.Formatters.Add(jsonFormatter);
			}

			
		}
예제 #22
0
        // GET api/<num>
        public HttpResponseMessage Get(int? id, string extension = "json")
        {
            var results = GetComputedResults(id);
            MediaTypeFormatter fmtr = null;

            switch (extension)
            {
                case "plain-text":
                    //TODO: write formatter
                    fmtr = new PlainTextMediaFormatter();
                    break;
                case "xml":
                    fmtr = new XmlMediaTypeFormatter() { UseXmlSerializer = true };
                    break;
                case "json":
                    fmtr = new JsonMediaTypeFormatter();
                    JsonMediaTypeFormatter f = fmtr as JsonMediaTypeFormatter;
                    break;
            }

            if (fmtr == null)
            {
                return new HttpResponseMessage(HttpStatusCode.NotFound);
            }

            return new HttpResponseMessage()
            {
                Content = new ObjectContent<FibonacciResultSet>(
                    results,
                    fmtr
                )
            };
        }
예제 #23
0
 private static HttpResponseMessage BuildContent(IEnumerable<string> messages)
 {
     var exceptionMessage = new ExceptionResponse { Messages = messages };
     var formatter = new JsonMediaTypeFormatter();
     var content = new ObjectContent<ExceptionResponse>(exceptionMessage, formatter, "application/json");
     return new HttpResponseMessage { Content = content };
 }
예제 #24
0
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

            var jsonFormatter = new JsonMediaTypeFormatter();
            config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
        }
예제 #25
0
        /// <summary>
        ///     Registers the specified configuration.
        /// </summary>
        /// <param name="config">The configuration.</param>
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.UseOrderedFilter();
            JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter
            {
                SerializerSettings =
                {
                    NullValueHandling = NullValueHandling.Include,
                    DateFormatString = "G",
                    DefaultValueHandling = DefaultValueHandling.Populate,
                    Formatting = Formatting.None,
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                }
            };

            config.Filters.Add(new GlobalExceptionFilterAttribute());

            config.Formatters.Clear();
            config.Formatters.Add(formatter);

            config.EnableCors(new EnableCorsAttribute("*", "*", "GET,POST,PUT,OPTIONS", "*"));

            SystemDiagnosticsTraceWriter traceWriter = config.EnableSystemDiagnosticsTracing();
            traceWriter.IsVerbose = true;
            traceWriter.MinimumLevel = TraceLevel.Info;

            // Web API routes
            config.MapHttpAttributeRoutes();
        }
        private static void AddDataControllerFormatters(List<MediaTypeFormatter> formatters, DataControllerDescription description)
        {
            var cachedSerializers = _serializerCache.GetOrAdd(description.ControllerType, controllerType =>
            {
                // for the specified controller type, set the serializers for the built
                // in framework types
                List<SerializerInfo> serializers = new List<SerializerInfo>();

                Type[] exposedTypes = description.EntityTypes.ToArray();
                serializers.Add(GetSerializerInfo(typeof(ChangeSetEntry[]), exposedTypes));

                return serializers;
            });

            JsonMediaTypeFormatter formatterJson = new JsonMediaTypeFormatter();
            formatterJson.SerializerSettings = new JsonSerializerSettings() { PreserveReferencesHandling = PreserveReferencesHandling.Objects, TypeNameHandling = TypeNameHandling.All };

            XmlMediaTypeFormatter formatterXml = new XmlMediaTypeFormatter();

            // apply the serializers to configuration
            foreach (var serializerInfo in cachedSerializers)
            {
                formatterXml.SetSerializer(serializerInfo.ObjectType, serializerInfo.XmlSerializer);
            }

            formatters.Add(formatterJson);
            formatters.Add(formatterXml);
        }
예제 #27
0
 public JsonContentNegotiator()
 {
     formatter = new JsonMediaTypeFormatter();
     // TODO: Make Configurable
     formatter.Indent = true;
     formatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
 }
예제 #28
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            GlobalConfiguration.Configuration.Formatters.Clear();
            var formatter = new JsonMediaTypeFormatter
                                {
                                    SerializerSettings =
                                        new JsonSerializerSettings
                                            {
                                                PreserveReferencesHandling =
                                                    PreserveReferencesHandling.Objects
                                            }
                                };

            GlobalConfiguration.Configuration.Formatters.Add(formatter);

            // OData
            var builder = new ODataConventionModelBuilder();
            builder.EntitySet<UserDevice>("UserDevice");
            builder.EntitySet<UserInformation>("UserInformation");
            config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel());

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
예제 #29
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();
            config.EnableCors();
            
            var kernel = ApiSetup.CreateKernel();

            var resolver = new NinjectDependencyResolver(kernel);

            var jsonFormatter = new JsonMediaTypeFormatter();
            jsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
            config.Formatters.Add(jsonFormatter);

            //setup dependency resolver for API           
            config.DependencyResolver = resolver;
            //setup dependency for UI controllers
            //DependencyResolver.SetResolver(resolver.GetService, resolver.GetServices);

            foreach (var item in GlobalConfiguration.Configuration.Formatters)
            {
                if (typeof (JsonMediaTypeFormatter) == item.GetType())
                {
                    item.AddQueryStringMapping("responseType", "json", "application/json");
                }
            }
        }
예제 #30
0
        protected virtual System.Net.Http.HttpResponseMessage GetResponseMessage <T>(string requestUri, T postData)
        {
            HttpClient client = new HttpClient();

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(ContentType.AsContentTypeString()));
            if (AuthenticationMethod == AuthenticationType.OAuth && !string.IsNullOrEmpty(_bearerToken))
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _bearerToken);
            }

            MediaTypeFormatter mediaFormatter;

            if (ContentType == RequestContentType.ApplicationXml)
            {
                mediaFormatter = new System.Net.Http.Formatting.XmlMediaTypeFormatter();
            }
            else
            {
                mediaFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter();
            }


            HttpResponseMessage responseMsg = null;

            if (OperationMethod == HttpMethod.Get)
            {
                responseMsg = client.GetAsync(requestUri).Result;
            }
            else if (OperationMethod == HttpMethod.Delete && postData == null)
            {
                responseMsg = client.DeleteAsync(requestUri).Result;
            }
            else if (OperationMethod == HttpMethod.Head)
            {
                var rqstMsg = new HttpRequestMessage(HttpMethod.Head, requestUri);
                responseMsg = client.SendAsync(rqstMsg).Result;
            }
            else
            {
                //Note: Need to explicitly specify the content type here otherwise this call fails.
                if (OperationMethod == HttpMethod.Put)
                {
                    responseMsg = client.PutAsync <T>(requestUri, postData, mediaFormatter).Result;
                }
                else
                {
                    responseMsg = client.PostAsync <T>(requestUri, postData, mediaFormatter).Result;
                }
            }

            return(responseMsg);
        }
예제 #31
0
        public static void Main(string[] args)
        {
            string url = @"http://localhost:10512/api/values";


            Person personToPost = new Person {
                FirstName = "first name here",
                LastName  = "last name here",
                Id        = new Random().Next()
            };


            var jsonFormatter  = new System.Net.Http.Formatting.JsonMediaTypeFormatter();
            var mediaType      = new MediaTypeHeaderValue("application/json");
            var requestMessage = new HttpRequestMessage <Person>(
                personToPost,
                mediaType,
                new MediaTypeFormatter[] { jsonFormatter });

            HttpClient          client   = null;
            HttpResponseMessage response = null;

            try {
                client = new HttpClient();
                Task postTask = client.PostAsync(url, requestMessage.Content).ContinueWith(respMsg => {
                    response = respMsg.Result;
                });

                postTask.Wait();

                Console.WriteLine(string.Format("Response status code: {0}", response.StatusCode));
                response.EnsureSuccessStatusCode();
            }
            catch (Exception ex) {
                string message = string.Format("An error occurred: {0}{1}{0}]", Environment.NewLine, ex.Message);
            }
            finally {
                if (client != null)
                {
                    client.Dispose();
                    client = null;
                }
            }

            Console.WriteLine("Press enter to continue");
            Console.ReadLine();
        }
예제 #32
0
 static JsonExtensions()
 {
     System.Net.Http.Formatting.JsonMediaTypeFormatter mediaTypeFormatter1 = new System.Net.Http.Formatting.JsonMediaTypeFormatter();
     mediaTypeFormatter1.SerializerSettings            = JsonExtensions.ObjectSerializationSettings;
     mediaTypeFormatter1.UseDataContractJsonSerializer = false;
     JsonExtensions.JsonObjectTypeFormatter            = (MediaTypeFormatter)mediaTypeFormatter1;
     JsonExtensions.JsonObjectTypeFormatters           = new MediaTypeFormatter[1]
     {
         JsonExtensions.JsonObjectTypeFormatter
     };
     System.Net.Http.Formatting.JsonMediaTypeFormatter mediaTypeFormatter2 = new System.Net.Http.Formatting.JsonMediaTypeFormatter();
     mediaTypeFormatter2.SerializerSettings            = JsonExtensions.MediaTypeFormatterSettings;
     mediaTypeFormatter2.UseDataContractJsonSerializer = false;
     JsonExtensions.JsonMediaTypeFormatter             = (MediaTypeFormatter)mediaTypeFormatter2;
     JsonExtensions.JsonMediaTypeFormatters            = new MediaTypeFormatter[1]
     {
         JsonExtensions.JsonMediaTypeFormatter
     };
 }
예제 #33
0
        public override bool Execute()
        {
            HttpClient client = null;

            try {
                var jsonFormatter          = new System.Net.Http.Formatting.JsonMediaTypeFormatter();
                var mediaType              = new MediaTypeHeaderValue("application/json");
                var jsonSerializerSettings = new JsonSerializerSettings();
                var requestMessage         = new HttpRequestMessage <string>(
                    this.PostContent,
                    mediaType,
                    new MediaTypeFormatter[] { jsonFormatter });

                client = new HttpClient();
                HttpResponseMessage         response = null;
                System.Threading.Tasks.Task postTask = client.PostAsync(this.Url, requestMessage.Content).ContinueWith(respMessage => {
                    response = respMessage.Result;
                });

                System.Threading.Tasks.Task.WaitAll(new System.Threading.Tasks.Task[] { postTask });

                response.EnsureSuccessStatusCode();

                return(true);
            }
            catch (Exception ex) {
                string message = "Unable to post the message.";
                throw new LoggerException(message, ex);
            }
            finally {
                if (client != null)
                {
                    client.Dispose();
                    client = null;
                }
            }
        }
예제 #34
-1
        public HttpResponseMessage Get()
        {
            try
            {
                var formatter = new JsonMediaTypeFormatter();
                var json = formatter.SerializerSettings;
                json.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
                json.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
                json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
                json.Formatting = Newtonsoft.Json.Formatting.Indented;
                json.ContractResolver = new CamelCasePropertyNamesContractResolver();

                var categories =
                    _bhtaEntities.Categories.ToList()
                        .Select(
                            m =>
                                new CategoryModel()
                                {
                                    Id = m.Id,
                                    Name = m.Name,
                                    Description = m.Description,
                                    Permalink = m.Permalink
                                });

                return Request.CreateResponse(HttpStatusCode.OK, categories, formatter);
            }
            catch (Exception exception)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exception.ToString());
            }
        }