5.WebAPI的Filter
1.WebApi的Filter介绍:
大家知道什么是AOP(aspect oriented programming)吗?它是可以通过预编译方式和运行期动态代理实现在不修改源代码的情况下给程序动态统一添加功能的一种技术。它是一种新的方法论,它是对传统OOP(object oriented programming)编程的一种补充。OOP是关注将需求功能划分为不同的并且相对独立,封装良好的类,并让它们有着属于自己的行为,依靠继承和多态等来定义彼此的关系;AOP是希望能够将通用需求功能从不相关的类当中分离出来,能够使得很多类共享一个行为,一旦发生变化,不必修改很多类,而只需要修改这个行为即可。AOP是使用切面(aspect)将横切关注点模块化,OOP是使用类将状态和行为模块化。在OOP的世界中,程序都是通过类和接口组织的,使用它们实现程序的核心业务逻辑是十分合适。但是对于实现横切关注点(跨越应用程序多个模块的功能需求)则十分吃力,比如日志记录,权限验证,异常拦截等。而Filter恰好体现的AOP思想(也可以说是一夫当关万夫莫开了)。
2.Filter的功能主要有:
(1)验证用户是否登录,如果用户没有登录,系统直接跳转到登录页面。
(2)权限控制。
(3)记录日志。
(4)异常处理。
3.Filer权限控制实现:
项目结构如图
(1)创建一个webapi项目并添加控制器
public class LoginController : ApiController
{
[HttpGet]
public string ToLogin(string username)
{
return username+",你好登录成功!";
}
}
(2)添加MyAuthorFilter类
public class MyAuthorFilter : IAuthorizationFilter
{
public bool AllowMultiple
{
//get { throw new NotImplementedException(); }
get { return true; }
}
public async Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
{
IEnumerable<string> values;
if (actionContext.Request.Headers.TryGetValues("UserName", out values))
{
string userName = values.FirstOrDefault();
if (userName != "ych")
{
return new
HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
}
}
else
{
return new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
}
return await continuation();
} }
(3)设置路由保证被注册
public static void Register(HttpConfiguration config)
{
// Web API 配置和服务 // Web API 路由
config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Filters.Add(new MyAuthorFilter());
}
请求结果:

4.Filer异常处理实现:
项目结构如图
(1)创建一个webapi项目并添加控制器
public class LoginController : ApiController
{
[HttpGet]
public string ToLogin(string username)
{
throw new Exception("抛异常," + username);
}
}
(2)添加MyExceptionFilter类
public class MyExceptionFilter : IExceptionFilter
{
//public bool AllowMultiple=>true;
public bool AllowMultiple
{
get { return true; }
}
public async Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
{
Exception ex = actionExecutedContext.Exception;
}
}
(3)设置路由保证被注册
public static void Register(HttpConfiguration config)
{
// Web API 配置和服务 // Web API 路由
config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Filters.Add(new MyExceptionFilter());
}
(4)用postman请求(http://localhost:43417/api/Login/tologin?username=qq)如图

这样就讲完了,你可以自己将异常什么的记录日志哦,活学活用才是硬道理!
5.WebAPI的Filter的更多相关文章
- ASP.NET WebAPI 13 Filter
Filter(筛选器)是基于AOP(面向方面编程)的设计,它的作用是Actionr的执行注入额外的逻辑,以达到横切注入的目的. IFilter 在WebAPI中所以的Filter都实现了IFilter ...
- 陨石坑之webapi使用filter
首先为什么说这是一个坑,是因为我们在webapi中使用filter的时候也许会先百度一下,好吧,挖坑的来了,我看了好几篇文章写的是使用System.Web.Mvc.Filters.ActionFilt ...
- Asp.Net WebAPI中Filter过滤器的使用以及执行顺序
转发自:http://www.cnblogs.com/UliiAn/p/5402146.html 在WEB Api中,引入了面向切面编程(AOP)的思想,在某些特定的位置可以插入特定的Filter进行 ...
- 陨石坑之webapi 使用filter中如何结束请求流
先看下正常的结束asp.net 请求流怎么写的 System.Web.HttpContext.Current.Response.Write(“end”); System.Web.HttpContext ...
- webapi自定义Filter
public class MyAutorFilter : IAuthorizationFilter { public bool AllowMultiple => true; public asy ...
- 在MVC或WEBAPI中记录每个Action的执行时间和记录下层方法调用时间
刚才在博客园看了篇文章,http://www.cnblogs.com/cmt/p/csharp_regex_timeout.html 突然联想到以前遇到的问题,w3wp进程吃光CPU都挂起IIS进程 ...
- System.Web.Mvc 和 using System.Net.Http 的 Filter
在尝试给webapi增加 ExceptionFilter时,出现了错误,经查询区别如下: System.Web.Mvc.Filters 是给mvc用的 System.Web.Http.Filters ...
- WebApi接口安全性 接口权限调用、参数防篡改防止恶意调用
背景介绍 最近使用WebApi开发一套对外接口,主要是数据的外送以及结果回传,接口没什么难度,采用WebApi+EF的架构简单创建一个模板工程,使用template生成一套WebApi接口,去掉put ...
- django 操作数据库--orm(object relation mapping)---models
思想 django为使用一种新的方式,即:关系对象映射(Object Relational Mapping,简称ORM). PHP:activerecord Java:Hibernate C#:Ent ...
随机推荐
- Ubuntu 分辨率更改 xrandr Failed to get size of gamma for output default
sudo vim /etc/xorg.conf copy: Section "Monitor" Identifier "Monitor0" VendorName ...
- Super Star(最小球覆盖)
Super Star http://poj.org/problem?id=2069 Time Limit: 1000MS Memory Limit: 65536K Total Submission ...
- Spring Boot中使用Websocket搭建即时聊天系统
1.首先在pom文件中引入Webscoekt的依赖 <!-- websocket依赖 --> <dependency> <groupId>org.springfra ...
- CSS文字大小单位px、em、pt详解
这里引用的是Jorux的“95%的中国网站需要重写CSS”的文章,题目有点吓人,但是确实是现在国内网页制作方面的一些缺陷.我一直也搞不清楚px与em之间的关系和特点,看过以后确实收获很大.平时都是用p ...
- UVa 1595 Symmetry(set)
We call a figure made of points is left-right symmetric as it is possible to fold the sheet of paper ...
- [leetcode]173. Binary Search Tree Iterator 二叉搜索树迭代器
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...
- 9-最短路径(dijkstra)
参考博客:http://www.wutianqi.com/?p=1890 #include <iostream>using namespace std;#define max 1< ...
- c语言定义函数指针和typedef简写
二种方法来定义函数指针 #include<stdio.h> #include<stdlib.h> #include<Windows.h> int add(int a ...
- canvas学习持续更新
参考:菜鸟教程,canvas教程 绘制一个简单的矩形 <body> <canvas id="myCanvas" width="200" hei ...
- Js中的this关键字(吉木自学)
研究生毕业答辩完,开始继续为转行努力.小白要奋斗了,加油.本文引自JS核心系列:浅谈函数的作用域. 在一个函数中,this总是指向当前函数的所有者对象,this总是在运行时才能确定其具体的指向, 也才 ...