当前位置: 首页>>代码示例>>C#>>正文


C# Formatting.JsonMediaTypeFormatter类代码示例

本文整理汇总了C#中System.Net.Http.Formatting.JsonMediaTypeFormatter的典型用法代码示例。如果您正苦于以下问题:C# JsonMediaTypeFormatter类的具体用法?C# JsonMediaTypeFormatter怎么用?C# JsonMediaTypeFormatter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


JsonMediaTypeFormatter类属于System.Net.Http.Formatting命名空间,在下文中一共展示了JsonMediaTypeFormatter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Get

        // 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 = "imperugo",
                    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);
        }
开发者ID:sunilmunikar,项目名称:BestPractices,代码行数:31,代码来源:ValuesController.cs

示例2: UseJsonOnly

 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);
 }
开发者ID:ChristianWeyer,项目名称:myProducts-End-to-End,代码行数:7,代码来源:HttpConfigurationExtensions.cs

示例3: ConfigureWebApi

    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);
    }
开发者ID:yuanfei05,项目名称:vita,代码行数:26,代码来源:WebHelper.cs

示例4: Configuration

        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);
        }
开发者ID:SergeBekenkamp,项目名称:DungeonsAndDragons5eCharacterEditor,代码行数:30,代码来源:Startup.cs

示例5: TestMethod1

        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);
            }
        }
开发者ID:sanghyukp,项目名称:AngularJSWebAPI2,代码行数:33,代码来源:UnitTest1.cs

示例6: Register

        /// <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();
        }
开发者ID:votrongdao,项目名称:cheping,代码行数:34,代码来源:WebApiConfig.cs

示例7: Register

        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;
            }
        }
开发者ID:pceftpos,项目名称:pay-at-table,代码行数:60,代码来源:WebApiConfig.cs

示例8: Register

        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");
                }
            }
        }
开发者ID:girmateshe,项目名称:OAuth,代码行数:29,代码来源:WebApiConfig.cs

示例9: Register

		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);
			}

			
		}
开发者ID:TomaszKorecki,项目名称:connectYourself,代码行数:25,代码来源:WebApiConfig.cs

示例10: Register

        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));
        }
开发者ID:bouwe77,项目名称:fmg,代码行数:28,代码来源:WebApiConfig.cs

示例11: BuildContent

 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 };
 }
开发者ID:fgNv,项目名称:SoccerFanTest,代码行数:7,代码来源:ExceptionHandling.cs

示例12: Register

        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 }
            );
        }
开发者ID:roylanceMichael,项目名称:GetFit,代码行数:31,代码来源:WebApiConfig.cs

示例13: AddDataControllerFormatters

        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);
        }
开发者ID:marojeri,项目名称:aspnetwebstack,代码行数:28,代码来源:DataControllerConfigurationAttribute.cs

示例14: CreateErrorResponse

        /// <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);
        }
开发者ID:sudarsanan-krishnan,项目名称:DynamicsCRMConnector,代码行数:13,代码来源:HttpHelpers.cs

示例15: GetUser

        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")
            };
        }
开发者ID:azlicn,项目名称:TeamThing,代码行数:25,代码来源:GoogleAuthProvider.cs


注:本文中的System.Net.Http.Formatting.JsonMediaTypeFormatter类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。