I am using Owin to build a self hosted server which support both file requests and web api. But the output for web api requests are always in xml format. How can I configure owin to output in json?
The code is as below:
class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseFileServer(new FileServerOptions()
{
RequestPath = PathString.Empty,
FileSystem = new PhysicalFileSystem(@".\files")
});
// set the default page
app.UseWelcomePage(@"/index.html");
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute
(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
app.UseWebApi(config);
}
}
I have found the answer myself. All have to do is to add a json formatter as below:
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
config.Formatters.JsonFormatter.SerializerSettings =
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
If need to convert enum to string add StringEnumConverter to the settings.
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With