1、概述api
2、什麼是XSSide
3、預防方法spa
4、在WebApi中如何實現code
在實現以前,須要瞭解ASP.NET WEB API的pipeline機制。
blog
如上,能夠採用多種方式進行參數的過濾ip
一、重寫DelegatingHandler的SendAsync方法進行過濾,結合AntiXss類庫實現ci
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using System.Web.Http.Controllers; using Microsoft.Security.Application; using System.Reflection; using System.ComponentModel; using System.Threading; using System.Net.Http; namespace MyNamespace { public class AntiXssHttpMessageHandler : DelegatingHandler { protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage Request, System.Threading.CancellationToken cancellationToken) { foreach (var key in Request.RequestUri.ParseQueryString().AllKeys) { var value = Sanitizer.GetSafeHtmlFragment(Request.RequestUri.ParseQueryString()[key]); if (value != Request.RequestUri.ParseQueryString()[key]) { throw new Exception(); } } return base.SendAsync(Request, cancellationToken); } } }
public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.EnableSystemDiagnosticsTracing(); config.MessageHandlers.Add(new AntiXssHttpMessageHandler()); } }
二、重寫ApiControllerActionInvoker的InvokeActionAsync方法string
public class XssActionInvoker : ApiControllerActionInvoker { public override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> InvokeActionAsync(HttpActionContext filterContext, System.Threading.CancellationToken cancellationToken) { Dictionary<string, object> changeDictionary = new Dictionary<string, object>(); foreach (var para in filterContext.ActionArguments) { if (para.Value.GetType()==typeof(string)) { var value = para.Value as string; if (!string.IsNullOrWhiteSpace(value)) { value = Sanitizer.GetSafeHtmlFragment(value); changeDictionary.Add(para.Key, value); } } } foreach (var changePara in changeDictionary) { filterContext.ActionArguments[changePara.Key] = changePara.Value; } return base.InvokeActionAsync(filterContext, cancellationToken); } }
public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpActionInvoker), new XssActionInvoker()); } }