【发布时间】:2016-04-29 15:08:52
【问题描述】:
我似乎无法在 Azure 移动应用中自定义 JSON 序列化。
为了避免我自己的代码过于复杂,我从头开始设置一个新项目。 Visual Studio Community 2015 Update 2,Azure App Service Tools v2.9(如果重要的话)。新项目、Visual C#、云、Azure 移动应用。
在App_Start\Startup.MobileApp.cs 中,这是模板中的内容:
public static void ConfigureMobileApp(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
new MobileAppConfiguration()
.UseDefaultConfiguration()
.ApplyTo(config);
// Use Entity Framework Code First to create database tables based on your DbContext
Database.SetInitializer(new MobileServiceInitializer());
MobileAppSettingsDictionary settings = config.GetMobileAppSettingsProvider().GetMobileAppSettings();
if (string.IsNullOrEmpty(settings.HostName))
{
app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions
{
// This middleware is intended to be used locally for debugging. By default, HostName will
// only have a value when running in an App Service application.
SigningKey = ConfigurationManager.AppSettings["SigningKey"],
ValidAudiences = new[] { ConfigurationManager.AppSettings["ValidAudience"] },
ValidIssuers = new[] { ConfigurationManager.AppSettings["ValidIssuer"] },
TokenHandler = config.GetAppServiceTokenHandler()
});
}
app.UseWebApi(config);
}
这是我尝试过的:
public static void ConfigureMobileApp(IAppBuilder app)
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings()
{
Converters = { new StringEnumConverter { CamelCaseText = true }, },
ContractResolver = new CamelCasePropertyNamesContractResolver { IgnoreSerializableAttribute = true },
DefaultValueHandling = DefaultValueHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore,
Formatting = Formatting.Indented
};
HttpConfiguration config = new HttpConfiguration();
config.Formatters.JsonFormatter.SerializerSettings = JsonConvert.DefaultSettings();
new MobileAppConfiguration()
.UseDefaultConfiguration()
.ApplyTo(config);
...
}
运行这个并访问http://localhost:53370/tables/TodoItem,json没有缩进,并且有一堆false字段,这表明设置被忽略了。
那么如何更改序列化程序设置,以便在此配置中尊重它们?从每个控制器返回一个带有我自己的自定义设置的JsonResult 是可行的,但只允许我发送200 OK 状态(我必须跳过箍返回一个尊重我的设置的201 Created)。
【问题讨论】:
-
您解决了这个问题吗?我似乎遇到了类似的问题,即移动应用程序不尊重我的序列化程序设置。在我的情况下,引用循环处理不起作用导致 500 个响应。