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. 在Oracle中执行动态SQL的几种方法

    转载:在Oracle中执行动态SQL的几种方法 以下为内容留存: 在Oracle中执行动态SQL的几种方法 在一般的sql操作中,sql语句基本上都是固定的,如:SELECT t.empno,t.en ...

  2. 请允许我转载一篇关于套接字的博客:Socket

    这一篇文章,我将图文并茂地介绍Socket编程的基础知识,我相信,如果你按照步骤做完实验,一定可以对Socket编程有更好地理解. 本文源代码,可以通过这里下载 http://files.cnblog ...

  3. dotnetcore/CAP

    CAP带你轻松玩转Asp.Net Core消息队列 CAP是什么? CAP是由我们园子里的杨晓东大神开发出来的一套分布式事务的决绝方案,是.Net Core Community中的第一个千星项目(目前 ...

  4. supervisord监控服务必备命令

    supervisord(http://supervisord.org/introduction.html)是一个非常优秀的进程管理工具,使用Python开发.它可以在类UNIX系统的方式让用户来准确地 ...

  5. 【下一代核心技术DevOps】:(六)Rancher集中存储及相关应用

    1. 前言 为什么要使用集中存储? 使用集中存储有个很大的优势是数据安全和统一管理,和集群完美配合. 产品集成存储经历过几个阶段: 1.单机本机存储. 系统使用本地硬盘存储 2.单网络集中存储. 局域 ...

  6. Python - 列表解析式

    列表解析——用来动态地创建列表 [expr for iter_var in iterable if cond_expr] 例子一: map(lambda x: x**2, range(6)) [0, ...

  7. Docker容器学习梳理 - 容器硬盘热扩容

    前面已介绍了docker很多知识点的操作记录,今天这里梳理下docker容器空间扩展的操作.默认情况下,物理机下创建的docker容器的空间是10G(虚拟机下创建的docker容器空间就是虚拟机的空间 ...

  8. C_数据结构_递归A函数调用B函数

    # include <stdio.h> int g(int); int f(int); int f(int n) { ) printf("haha\n"); else ...

  9. 关于Runtime error

    别人说的,但我感觉是因为你的操作是不符合语言规定的,让编译器无法识别,运行不出

  10. js 时间戳转换为日期格式

     //将1525854409000类型的时间转换成“yyyy-MM-dd”或“yyyy-MM-dd hh:mm:ss”   //info.birthday是后台获取到的Date类型的出生日期数据, / ...