必需的原语依赖项没有显式定义
本文关键字:定义 原语 依赖 | 更新日期: 2023-09-27 18:16:04
我有Asp。asp.net MVC应用程序,我使用了structuremap,我使用自定义ThrottleAttribute ActionFilter。asp.net mvc中的跟随速率限制
public enum TimeUnit
{
Minute = 60,
Hour = 3600,
Day = 86400
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class ThrottleAttribute : ActionFilterAttribute
{
public TimeUnit Time { get; set; }
public int Count { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var seconds = Convert.ToInt32(Time);
var key = string.Join(
"-",
seconds,
filterContext.HttpContext.Request.HttpMethod,
filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
filterContext.ActionDescriptor.ActionName,
filterContext.HttpContext.Request.UserHostAddress
);
// increment the cache value
var cnt = 1;
if (HttpRuntime.Cache[key] != null)
{
cnt = (int)HttpRuntime.Cache[key] + 1;
}
HttpRuntime.Cache.Insert(
key,
cnt,
null,
DateTime.UtcNow.AddSeconds(seconds),
Cache.NoSlidingExpiration,
CacheItemPriority.Low,
null
);
if (cnt >= Count)
{
filterContext.Result = new ContentResult
{
Content = "You are allowed to make only " + Count + " requests per " + Time.ToString().ToLower()
};
filterContext.HttpContext.Response.StatusCode = 429;
}
}
}
使用ThrottleAttribute后抛出Exception:
Setter属性'Time' (ActionFilters.TimeUnit):必需的基本依赖项没有明确定义
和我的ActionFilter Registry:
public class ActionFilterRegisteryClass : StructureMap.Registry
{
public ActionFilterRegisteryClass(Func<StructureMap.IContainer> containerFactory)
{
For<IFilterProvider>().Use(
new StructurMapFilterProvider(containerFactory));
Policies.SetAllProperties(x =>
{
x.Matching(p =>
p.DeclaringType.CanBeCastTo(typeof(ActionFilterAttribute)) &&
(
p.DeclaringType.Namespace.StartsWith("MyNamespace")
) &&
!p.PropertyType.IsPrimitive &&
p.PropertyType != typeof(string)
);
});
}
}
Exception is fire in: container.积聚(filter.Instance);
public class StructurMapFilterProvider : FilterAttributeFilterProvider
{
private readonly Func<StructureMap.IContainer> _Container;
public StructurMapFilterProvider(Func<StructureMap.IContainer> container)
{
_Container = container;
}
public override IEnumerable<Filter> GetFilters(ControllerContext controllerContext,
ActionDescriptor actionDescriptor)
{
var filters = base.GetFilters(controllerContext, actionDescriptor);
var container = _Container();
foreach (var filter in filters)
{
container.BuildUp(filter.Instance);
yield return filter;
}
}
}
Setter属性'Time' (ActionFilters.TimeUnit):必需的基本依赖项没有明确定义
我该怎么办?
如何显式定义PrimitiveTypes?
问题是在structuremap中注册ActionFilterClass。我将其修改如下:
public class ActionFilterRegisteryClass : StructureMap.Registry
{
public ActionFilterRegisteryClass(Func<StructureMap.IContainer> containerFactory)
{
For<IFilterProvider>().Use(
new StructurMapFilterProvider(containerFactory));
Policies.SetAllProperties(x =>
{
x.Matching(p =>
p.DeclaringType.CanBeCastTo(
!p.PropertyType.IsPrimitive &&
!p.PropertyType.IsEnum &&
p.PropertyType != typeof(string));
});
}
}