ارتقاء به ASP.NET Core 1.0 - قسمت 20 - بررسی تغییرات فیلترها
نویسنده: وحید نصیری
تاریخ: ۱۳۹۵/۰۵/۰۴ ۱۵:۲۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
namespace FiltersSample.Filters
{
public class SampleActionFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
// انجام کاری پیش از اجرای اکشن متد
}
public void OnActionExecuted(ActionExecutedContext context)
{
// انجام کاری پس از اجرای اکشن متد
}
}
} namespace FiltersSample.Filters
{
public class SampleAsyncActionFilter : IAsyncActionFilter
{
public async Task OnActionExecutionAsync(
ActionExecutingContext context,
ActionExecutionDelegate next)
{
// انجام کاری پیش از اجرای اکشن متد
await next();
// انجام کاری پس از اجرای اکشن متد
}
}
} using Microsoft.AspNetCore.Mvc.Filters;
namespace FiltersSample.Filters
{
public class AddHeaderAttribute : ResultFilterAttribute
{
private readonly string _name;
private readonly string _value;
public AddHeaderAttribute(string name, string value)
{
_name = name;
_value = value;
}
public override void OnResultExecuting(ResultExecutingContext context)
{
context.HttpContext.Response.Headers.Add(
_name, new string[] { _value });
base.OnResultExecuting(context);
}
}
} [AddHeader("Author", "DNT")]
public class SampleController : Controller
{
public IActionResult Index()
{
return Content("با فایرباگ هدر خروجی را بررسی کنید");
}
} public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.Filters.Add(typeof(SampleActionFilter)); // by type
options.Filters.Add(new SampleGlobalActionFilter()); // an instance
});
} [MyFilter(Name = "Method Level Attribute", Order=-1)]
[ServiceFilter(typeof(AddHeaderFilterWithDi))]
public IActionResult Index()
{
return View();
} services.AddScoped<AddHeaderFilterWithDi>();
System.InvalidOperationException: No service for type 'FiltersSample.Filters.AddHeaderFilterWithDI' has been registered.
[TypeFilter(typeof(AddHeaderAttribute), Arguments = new object[] { "Author", "DNT" })]
public IActionResult Hi(string name)
{
return Content($"Hi {name}");
} using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
namespace Core1RtmEmptyTest.StartupCustomizations
{
public class CustomExceptionLoggingFilterAttribute : ExceptionFilterAttribute
{
private readonly ILogger<CustomExceptionLoggingFilterAttribute> _logger;
public CustomExceptionLoggingFilterAttribute(ILogger<CustomExceptionLoggingFilterAttribute> logger)
{
_logger = logger;
}
public override void OnException(ExceptionContext context)
{
_logger.LogInformation($"OnException: {context.Exception}");
base.OnException(context);
}
}
} public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.Filters.Add(typeof(CustomExceptionLoggingFilterAttribute)); public void Configure(ILoggerFactory loggerFactory)
{
loggerFactory.AddDebug(minLevel: LogLevel.Debug); public IActionResult GetData()
{
throw new Exception("throwing an exception!");
}
public class CustomValidationAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var service = validationContext.GetService(typeof(IExternalService));
// use service
}
} var model = filterContext.ActionArguments.Select(item => item.Value).OfType<MyViewModelClass>().FirstOrDefault();
public class CustomActionFilter : Attribute, IActionFilter
{
private string _DesController;
private string _DesAction;
private readonly IPermission _Permission;
public CustomActionFilter(string DesController, string DesAction, IPermission Permission)
{
_DesController = DesController;
_DesAction = DesAction;
_Permission = Permission;
}
public void OnActionExecuted(ActionExecutedContext context)
{
} public class CustomActionFilterAttribute : Attribute, IActionFilter
{
private readonly string _param1;
private readonly string _param2;
private readonly IJob _job;
public CustomActionFilterAttribute(string param1, string param2, IJob job)
{
_param1 = param1;
_param2 = param2;
_job = job;
}
public void OnActionExecuted(ActionExecutedContext context)
{
throw new NotImplementedException();
}
public void OnActionExecuting(ActionExecutingContext context)
{
throw new NotImplementedException();
}
} public interface IJob
{
void Start();
}
public class Job1 : IJob
{
public void Start()
{
}
} public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IJob, Job1>(); [TypeFilter(typeof(CustomActionFilterAttribute),
Arguments = new object[] { "param1Value", "param2Value" })]
public IActionResult About()
{
public void OnActionExecuting(ActionExecutingContext context)
{
context.Result = new JsonResult(new { msg = "" });
} await next();
public class CheckUserIp : IAsyncActionFilter
{
private readonly string[] _bannedIps;
public CheckUserIp(params string[] bannedIps)
{
_bannedIps = bannedIps;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var userIp = context.HttpContext.Connection.RemoteIpAddress?.ToString() ?? string.Empty;
if (_bannedIps.Contains(userIp))
{
context.Result = new ViewResult()
{
ViewName = "Forbidden"
};
}
else
{
await next();
}
// await next(); => throw exception
}
} [TypeFilter(typeof(CheckUserIp), Arguments = new object[]{ new[] { "::1", "134.56.110.44" } })]
public IActionResult Index()
{
return View();
}