本文整理汇总了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);
}
示例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);
}
示例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);
}
示例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);
}
示例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);
}
}
示例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();
}
示例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;
}
}
示例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");
}
}
}
示例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);
}
}
示例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));
}
示例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 };
}
示例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 }
);
}
示例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);
}
示例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);
}
示例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")
};
}