Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Owin self host support Json output?

Tags:

asp.net

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);
    }
}
like image 866
Yang Zhang Avatar asked Oct 21 '14 22:10

Yang Zhang


1 Answers

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());
like image 189
Yang Zhang Avatar answered Nov 15 '22 05:11

Yang Zhang