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. easyui的datagrid的列checkbox自定义增加disabled选项

    需求根据权限判断datagrid的每一列的checkBox是否可选,看了下文档,发现editor的checkbox应该能实现这个功能,但我们项目自己将easyui外面包了一层,把原生的editor改成 ...

  2. 没有内涵段子可以刷了,利用Python爬取段友之家贴吧图片和小视频(含源码)

    由于最新的视频整顿风波,内涵段子APP被迫关闭,广大段友无家可归,但是最近发现了一个"段友"的app,版本更新也挺快,正在号召广大段友回家,如下图,有兴趣的可以下载看看(ps:我不 ...

  3. BZOJ 2810 [Apio2012]kunai

    Orz Starria 现在看来,也不是很难,能做...就是不能写 可以想到维护每个苦无扫过的矩形,然后做矩形面积并即可. 然后发现自己只会$n^2$的处理方法... 想了好久之后问了一发 Starr ...

  4. try--catch--finally中return返回值执行的顺序

    1.try块中没有抛出异常,try.catch和finally块中都有return语句 public static int NoException(){ int i=10; try{ System.o ...

  5. Stencil 基础

    Stencil 一个轻量化,渐进式编译器,注意,不是框架. 使用 TypeScript 进行所有操作,这是一个门槛,有一定技术门槛要求. PS:个人强烈推荐所有的前端同学都学习,或至少了解这个超集语言 ...

  6. Python基础(中)

    前言 print(" _ooOoo_ ") print(" o8888888o ") print(" 88 . 88 ") print(&q ...

  7. 大话重构连载15:采用Mock技术完成测试

    第五次重构我们引入了数据库的设计,用户信息要从数据库中读取,问候语库存储在数据库中,并支持添加与更新.数据库的引入使自动化测试变得困难了,因为数据状态总是变化着的,而这种变化使得测试过程不能复现,这是 ...

  8. Python_命名空间和作用域_25

    # 函数进阶 a = def func(): print(a) func() # 命名空间和作用域 # print() # input() # list # #命名空间 有三种 #内置命名空间 —— ...

  9. QQ使用的使用评价

    1:界面以及功能:打开软件之后探出登录窗口,基本功能的登录,找回密码,注册帐号等功能均在比较醒目的位置,界面较为友好. 将注册帐号放在打开软件的第一界面当然是正确的选择,给予用户非常直观的提示(没有帐 ...

  10. Ubuntu14.04安装PyMuPDF

    最近写的一个东西需要将pdf转成图片然后放在网页上展示,找到了个非常好用的轮子叫做PyMuPDF,在windows上测试的时候跑的666,在ubuntu上安装依赖的时候,简直万脸懵逼.github上给 ...