C# 带有筛选器的ServiceStack IP限制
在我的ServiceStack应用程序中,我试图重新通信所有用户,除了那些IP位于白名单中的用户,唯一的方法是在我的配置方法中使用PreRequestFilters:C# 带有筛选器的ServiceStack IP限制,c#,.net,servicestack,httpserver,C#,.net,servicestack,Httpserver,在我的ServiceStack应用程序中,我试图重新通信所有用户,除了那些IP位于白名单中的用户,唯一的方法是在我的配置方法中使用PreRequestFilters: PreRequestFilters.Add((req, res) => { if (!ipWhiteList.Contains(req.RemoteIp)) { res.ContentType = req.ResponseContentType; res.StatusCode
PreRequestFilters.Add((req, res) =>
{
if (!ipWhiteList.Contains(req.RemoteIp))
{
res.ContentType = req.ResponseContentType;
res.StatusCode = (int)HttpStatusCode.Unauthorized;
res.Dto = DtoUtils.CreateErrorResponse("401", "Unauthorized", null);
res.EndRequest();
}
});
这是否可以通过自定义身份验证过滤器实现(如果可能的话)?也许有一些现成的功能可以做到这一点,或者只需遵循最佳实践?您也可以为此使用,例如:
public class ValidateIpAttribute : RequestFilterAttribute
{
public IpValidator IpValidator { get; set; }
public void RequestFilter(IRequest req, IResponse res, object requestDto)
{
if (IpValidator.Allow(req.RemoteIp))
return;
res.ContentType = req.ResponseContentType;
res.StatusCode = (int)HttpStatusCode.Unauthorized;
res.Dto = DtoUtils.CreateErrorResponse("401", "Unauthorized", null);
res.EndRequest();
}
}
然后您可以在您的服务上使用,例如:
[ValidateIp]
public class ProtectedServices : Service
{
}
但此筛选器在授权尝试期间不会触发,对吗?@HardLuck默认情况下,它的优先级为
0
,在[Authenticate]
之后和服务执行之前执行。但即使我在筛选器中重新定义优先级,如public static new int Priority=>-2;它以前还没有运行过Authentication@HardLuck我链接到前面的[Authenticate]属性,其优先级为-100。优先级<0只是在全局请求筛选器之前执行。请求筛选器与身份验证无关,除非调用服务操作,否则不会启动,因此一切正常,谢谢