webapi的controller和action的控制。

使用场景:webapi接收到加密数据以及签名。验证签名是否有效。我们不能一个个action增加判断。

所以添加Filter是比较明智的方法。

首先 签名过滤器

namespace API.Filters
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class APISignAttribute : ActionFilterAttribute
{
public static readonly string APISign = WebConfigurationManager.AppSettings["APISign"]; public override void OnActionExecuting(HttpActionContext actionContext)
{ if (IsVaild(actionContext))
{
base.OnActionExecuting(actionContext);
}
else
{
throw new Exception("Invalid sign");
} } public bool IsVaild(HttpActionContext actionContext)
{
var sign = HttpContext.Current.Request.Form["data"].ToString();
//开始判断逻辑 return false;
} public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
// 若发生例外则不在这边处理
if (actionExecutedContext.Exception != null)
return; base.OnActionExecuted(actionExecutedContext);
}
}
}

异常过滤器

public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
base.OnException(actionExecutedContext); var result = new apiResult<object>()
{
code = HttpStatusCode.BadRequest,
msg = actionExecutedContext.Exception.Message
};
if (actionExecutedContext.Exception is InvalidTokenException)
{
result.code = HttpStatusCode.Unauthorized;
}
string msg = "\r\n" + "apiErrorHandelattribute.StackTrace:\r\n" + actionExecutedContext.Exception.StackTrace + "\r\n\r\n" + "Message:\r\n" + actionExecutedContext.Exception.Message + "\r\n\r\n";
LogerHelper.WriteLog(msg); // 重新打包回传的讯息
actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(result.code, result); }

然后是启用方式,有2种

1 全局控制 在webapiConfig中添加

config.Filters.Add(new APISignAttribute());
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
); //注册 sign统一验证
config.Filters.Add(new APISignAttribute()); //注册 api异常处理
//config.Filters.Add(new ApiErrorHandleAttribute());
}
}

2 局部的控制

加在action上代表需要进入filter

加在controller上,代表该controller中所有action都要进入filter

[APISignAttribute]
public class TestController : BaseControllerAPI
{
[HttpPost]
public dynamic Get()
{
apiResult<dynamic> result = new apiResult<dynamic>();
result.data= new List<string>() { "", "" }; return result; } [APISignAttribute]
[HttpGet]
public dynamic haha()
{
return "value1";
}
}

结束

webapi Filter的更多相关文章

  1. webapi filter过滤器中获得请求的方法详情(方法名,Attributes)

    public class GlobalActionFilter : ActionFilterAttribute { private string _requestId; public override ...

  2. 20、ASP.NET MVC入门到精通——WebAPI

    本系列目录:ASP.NET MVC4入门到精通系列目录汇总 微软有了Webservice和WCF,为什么还要有WebAPI? 用过WCF的人应该都清楚,面对那一大堆复杂的配置文件,有时候一出问题,真的 ...

  3. MVC—WebAPI(调用、授权)

    ASP.NET MVC—WebAPI(调用.授权)   本系列目录:ASP.NET MVC4入门到精通系列目录汇总 微软有了Webservice和WCF,为什么还要有WebAPI? 用过WCF的人应该 ...

  4. WebAPI的压缩

    看见老外写了一篇ASP.NET Web API GZip compression ActionFilter with 8 lines of code 说实话被这标题吸引了,8行代码实现GZip压缩过滤 ...

  5. WebAPI性能优化之压缩解压

    有时候为了提升WebAPI的性能,减少响应时间,我们会使用压缩和解压,而现在大多数客户端浏览器都提供了内置的解压支持.在WebAPI请求的资源越大时,使用压缩对性能提升的效果越明显,而当请求的资源很小 ...

  6. WebAPI性能优化

    WebAPI性能优化之压缩解压 有时候为了提升WebAPI的性能,减少响应时间,我们会使用压缩和解压,而现在大多数客户端浏览器都提供了内置的解压支持.在WebAPI请求的资源越大时,使用压缩对性能提升 ...

  7. c#权限验证

    在开发过程中,需要对访问者的身份做权限验证(再filter中进行权限过滤). 在每次进入控制器方法之前进行调用:如 [ControllerAuth] [RoutePrefix("Clinic ...

  8. asp.net web api 授权功能

    1.重写授权方法 using System; using System.Collections.Generic; using System.Linq; using System.Net; using ...

  9. SSM+Redis+Shiro+Maven框架搭建及集成应用

    引文: 本文主要讲述项目框架搭建时的一些简单的使用配置,教你如何快速进行项目框架搭建. 技术: Spring+SpringMVC+Mybatis+Redis+Shiro+Maven          ...

随机推荐

  1. Android BaseAdapter加载多个不同的Item布局时出现UncaughtException in Thread main java.lang.ArrayIndexOutOfBoundsException: length=15; index=15

    java.lang.ArrayIndexOutOfBoundsException: length=15; index=15 异常出现的场景:在做聊天界面时,需要插入表情,图片,文字,名片,还有几种较为 ...

  2. Oracle 在函数或存储过程中执行一条插入语句并返回主键ID值

    有时,我们需要往一张表插入一条记录,同时返回主键ID值. 假定主键ID的值都是通过对应表的SEQUENCE来获得,然后进行ID赋值 这里有几种情况需要注意: 1)如果建表语句含有主键ID的触发器,通过 ...

  3. Java 面试题 队列

    Queue: 基本上,一个队列就是一个先入先出(FIFO)的数据结构 Queue接口与List.Set同一级别,都是继承了Collection接口.LinkedList实现了Deque接 口.   Q ...

  4. 【Qt】窗口居中显示

    w.move((a.desktop()->width() - w.width())/, (a.desktop()->height() - w.height())/); 上述方法可以置中,但 ...

  5. CSS 内边距 (padding) 实例

    CSS 内边距 (padding) 实例元素的内边距在边框和内容区之间.控制该区域最简单的属性是 padding 属性. CSS padding 属性定义元素边框与元素内容之间的空白区域.CSS 内边 ...

  6. 基于Ping和Telnet/NC的监控脚本案例分析

    案例一:单纯地对某些ip进行ping监控 [root@test opt]# cat /opt/hosts_ip_list 192.168.10.10 192.168.10.11 192.168.10. ...

  7. gerrit代码简单备份方案分享

    由于前期部署了gerrit代码审核系统,开发调整后的线上代码都放到gerrit上,这就要求我们要保证代码的安全.所以,对gerrit代码的备份至关重要! 备份的策略是:1)先首次将gerrit项目代码 ...

  8. Gerrit上分支操作记录(创建分支、删除分支)

    Git分支对于一个项目的代码管理而言,是十分重要的!许多久用git的朋友可能已经掌握的很牢固了,但对于一些初涉git的童鞋来说,可能还不是很熟悉.在此,我将自己的一些操作经历做一梳理,希望能帮助到有用 ...

  9. Codeforces Round #503 (by SIS, Div. 2)-C. Elections

    枚举每个获胜的可能的票数+按照花费排序 #include<iostream> #include<stdio.h> #include<string.h> #inclu ...

  10. Android之JSON格式数据解析

    查看原文:http://blog.csdn.net/hantangsongming/article/details/42234293 JSON:JavaScript 对象表示法(JavaScript ...