在对外公布的Web API中,我们要实现合法性的校验。 每一个API都去写校验代码,有点那个...
很自然的,我们写一个中间的基类,继承自 ApiController,并在统一调用入口进行校验,如果不合法,就给出不合法的信息。
我使用的代码如下:
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
public class _ApiController : ApiController {
public override System.Threading.Tasks.Task<HttpResponseMessage> ExecuteAsync(System.Web.Http.Controllers.HttpControllerContext controllerContext, System.Threading.CancellationToken cancellationToken)
{
var httpContext = (HttpContextWrapper)controllerContext.Request.Properties["MS_HttpContext"];
string sig = httpContext.Request["sig"];
string client_ip = httpContext.Request.UserHostAddress;
if (client_ip != "127.0.0.1")
return Task.Factory.StartNew(() => { return controllerContext.Request.CreateErrorResponse(HttpStatusCode.Forbidden, "错误的客户端地址。"); }, cancellationToken);
if (sig != ".........")
return Task.Factory.StartNew(() => { return controllerContext.Request.CreateErrorResponse(HttpStatusCode.Forbidden, "错误的签名。"); }, cancellationToken);
return base.ExecuteAsync(controllerContext, cancellationToken);
}
}
红色的地方是我的纠结点。
参考文档:
http://www.strathweb.com/2012/05/implementing-message-handlers-to-track-your-asp-net-web-api-usage/