How to set custom JsonSerializerSettings for Json.NET in MVC 4 Web API? 控制ASP.NET Web API 调用频率

ou can customize the JsonSerializerSettings by using theFormatters.JsonFormatter.SerializerSettings property in the HttpConfiguration object.

For example, you could do that in the Application_Start() method:

protected void Application_Start()
{
    HttpConfiguration config = GlobalConfiguration.Configuration;
    config.Formatters.JsonFormatter.SerializerSettings.Formatting =
        Newtonsoft.Json.Formatting.Indented;
}


//---------------------------------------------------


很多的api,例如GitHub’s API 都有流量控制的做法。使用速率限制,以防止在很短的时间量客户端向你的api发出太多的请求.例如,我们可以限制匿名API客户端每小时最多60个请求,而我们可以让更多的经过认证的客户端发出更多的请求。那么asp.net webapi如何实现这样的功能呢?在项目WebApiContrib 上面已经有了一个实现:https://github.com/WebApiContrib/WebAPIContrib/blob/master/src/WebApiContrib/MessageHandlers/ThrottlingHandler.cs ,具有良好的可扩展性。

最简单的方法是使用ThrottlingHandler注册使用简单的参数,例如控制每个用户每小时60个请求:

config.MessageHandlers.Add(new ThrottlingHandler(
    new InMemoryThrottleStore(), 
     id => 60, 
    TimeSpan.FromHours(1)));
IThrottleStore接口 使用ID +当前的请求数量。InMemoryThrottleStore 只有一个内存中存储,但你可以轻松地扩展实现为分布式缓存或数据库。还可以轻松地自定义ThrottlingHandler的行为,例如我们针对一个ip地址可以更好的进行控制。

很多的api,例如GitHub’s API 都有流量控制的做法。使用速率限制,以防止在很短的时间量客户端向你的api发出太多的请求.例如,我们可以限制匿名API客户端每小时最多60个请求,而我们可以让更多的经过认证的客户端发出更多的请求。那么asp.net webapi如何实现这样的功能呢?在项目WebApiContrib 上面已经有了一个实现:https://github.com/WebApiContrib/WebAPIContrib/blob/master/src/WebApiContrib/MessageHandlers/ThrottlingHandler.cs ,具有良好的可扩展性。

最简单的方法是使用ThrottlingHandler注册使用简单的参数,例如控制每个用户每小时60个请求:

config.MessageHandlers.Add(new ThrottlingHandler(
    new InMemoryThrottleStore(), 
     id => 60, 
    TimeSpan.FromHours(1)));
IThrottleStore接口 使用ID +当前的请求数量。InMemoryThrottleStore 只有一个内存中存储,但你可以轻松地扩展实现为分布式缓存或数据库。还可以轻松地自定义ThrottlingHandler的行为,例如我们针对一个ip地址可以更好的进行控制。