12

下面是我的代码片段

模型类

// 客户.cs

using CommonLayer;

namespace Models
{
    public class Customer
    {
        public int Id { get; set; }

        [MyAntiXss]
        public string Name { get; set; }
    }
}

我想清理模型类的“名称”字段中的值,如下所示

// CutstomModelBinder.cs

 using Microsoft.Security.Application;
    using System.ComponentModel;
    using System.Linq;
    using System.Web.Mvc;

    namespace CommonLayer
    {
        public class CutstomModelBinder : DefaultModelBinder
        {
            protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
            {
                if (propertyDescriptor.Attributes.OfType<MyAntiXssAttribute>().Any())
                {
                    ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name);
                    string filteredValue = Encoder.HtmlEncode(valueResult.AttemptedValue);
                    propertyDescriptor.SetValue(bindingContext.Model, filteredValue);
                }
                else
                    base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
            }
        }
    }

我将“DefaultBinder”更改为我的“CutstomModelBinder”,如下所示

// Global.asax.cs

using CommonLayer;
using System.Web.Http;
using System.Web;
using System.Web.Mvc;

namespace WebAPI
{
    public class WebApiApplication : HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
            ModelBinders.Binders.DefaultBinder = new CutstomModelBinder();
        }
    }
}

我写了一个控制器类如下

// 客户控制器.cs

using Models;
using System.Collections.Generic;
using System.Web.Http;

namespace WebAPI.Controllers
{
    public class CustomerController : ApiController
    {
        public string Post([FromBody]Customer customer)
        {
            //customer.Name = Encoder.HtmlEncode(customer.Name);
            return string.Format("Id = {0}, Name = '{1}'", customer.Id, customer.Name);
        }
    }
}

当我如下调用上述控制器类的“Post”方法时,它正在按预期调用控制器类的“Post”方法。但它没有在我的“CutstomModelBinder”类中调用“BindProperty”方法。

// 程序.cs

using Models;
using System;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;

namespace Client
{
    public static class Program
    {
        public static void Main(params string[] args)
        {
            bool success = Post();
            Console.WriteLine("success = " + success);
            Console.Read();
        }

        private static HttpClient GetHttpClient()
        {
            HttpClient client = new HttpClient { BaseAddress = new Uri("http://localhost:49295/") };
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            return client;
        }

        private static bool Post()
        {
            Customer customer = new Customer { Id = 1, Name = "<br>Anivesh</br>" };
            HttpContent content = new ObjectContent<Customer>(customer, new JsonMediaTypeFormatter());

            HttpClient client = GetHttpClient();
            HttpResponseMessage response = client.PostAsync("Customer", content).Result;
            client.Dispose();

            if (response.IsSuccessStatusCode)
            {
                string expected = string.Format("Id = {0}, Name = '{1}'", customer.Id, customer.Name);
                string result = response.Content.ReadAsAsync<string>().Result;
                return expected == result;
            }
            else
                return false;
        }
    }
}

请让我知道使用“DataBinders”的正确方法,以便我可以在控制器中接收呼叫之前在一个公共位置清理输入数据。

4

3 回答 3

10

要使用 Web API 以通用方式清理输入,您可以按照我之前的回答中所述创建自己的 ModelBinder,但是更简单的方法可能是修改现有的 JsonMediaTypeFormatter 以在ReadFromStreamAsync方法中包含所需的清理逻辑。

您可以尝试的一种方法如下:

首先,创建一个通用属性,用于装饰 DTO 中需要清理的属性,即:

 [AttributeUsage(AttributeTargets.Property)]
 public sealed class SanitizeAttribute : Attribute
 { }

然后创建一个负责清理的 JsonMediaTypeFormatter 的子类型,即:

public sealed class SanitizingJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
    public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, CancellationToken cancellationToken)
    {
        Task<object> resultTask = base.ReadFromStreamAsync(type, readStream, content, formatterLogger, cancellationToken);

        var propertiesFlaggedForSanitization = type.GetProperties().Where(e => e.GetCustomAttribute<SanitizeAttribute>() != null).ToList();
        if (propertiesFlaggedForSanitization.Any())
        {
            var result = resultTask.Result;
            foreach (var propertyInfo in propertiesFlaggedForSanitization)
            {
                var raw = (string)propertyInfo.GetValue(result);
                if (!string.IsNullOrEmpty(raw))
                {
                    propertyInfo.SetValue(result, AntiXssEncoder.HtmlEncode(raw, true));
                }
            }
        }
        return resultTask;
    }
}

此实现仅检查生成的 Type 是否具有任何使用 Sanitize 属性修饰的属性,如果是,则使用内置 System.Web.Security.AntiXss.AntiXssEncoder(.NET 4.5 及更高版本)执行清理.

您可能会希望优化此类,以便它缓存类型和属性信息,这样您就不会在每次反序列化时进行繁重的反射调用。

该过程的最后一步是在 WebAPI 启动代码中将内置的 JSON 媒体类型格式化程序替换为您自己的格式化程序:

var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
config.Formatters.Remove(jsonFormatter);
config.Formatters.Add(new SanitizingJsonMediaTypeFormatter());

现在,任何具有用 Sanitize 属性修饰的属性的 DTO 都将在 DTO 到达您的控制器之前被正确编码。

于 2016-04-18T16:58:43.910 回答
4

.NetCore Web API 2. 使用 InputFormatter 递归地清理传入 JSON 的所有属性(任何深度)。

[AttributeUsage(AttributeTargets.Property)]
public sealed class SanitizePropertyAttribute : Attribute
{
}

public class SanitizeTextInputFormatter: Microsoft.AspNetCore.Mvc.Formatters.TextInputFormatter
{
    private List<String> ExcludeTypes = new List<string>()
    {
        "System.DateTime",
        "System.Int32",
        "System.Int64",
        "System.Boolean",
        "System.Char",
        "System.Object"
    };

    private string CleanInput(string strIn)
    {
        // Replace invalid characters with empty strings.
        try
        {
            // [<>/] or @"[^\w\.@-]"
            return Regex.Replace(strIn, @"[<>/]", "",
                                 RegexOptions.None, TimeSpan.FromSeconds(1.5));
        }
        // If we timeout when replacing invalid characters, 
        // we should return Empty.
        catch (RegexMatchTimeoutException)
        {
            return String.Empty;
        }
    }

    public SanitizeTextInputFormatter()
    {
        SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/json"));

        SupportedEncodings.Add(Encoding.UTF8);
        SupportedEncodings.Add(Encoding.Unicode);
    }

    private bool ValidateSanitizeProperty(Type type, PropertyInfo PropertyInfo, List<PropertyInfo> orgTypes)
    {
        var listedProperty = orgTypes.Where(_ => _ == PropertyInfo).FirstOrDefault();
        if (PropertyInfo != null && listedProperty == null) orgTypes.Add(PropertyInfo);

        if (listedProperty != null) return false;

        if (type.FullName == "System.String" && PropertyInfo != null)
        {
            var sanitizePropertyAttribute = PropertyInfo.GetCustomAttribute<SanitizePropertyAttribute>();
            //var sanitizeClassAttribute = PropertyInfo.CustomAttributes.Where(e => e.AttributeType == typeof(SanitizePropertyAttribute)).FirstOrDefault();

            return sanitizePropertyAttribute != null;
        }

        var typeProperties = type.GetProperties().Where(_ => _.PropertyType.IsAnsiClass == true && !ExcludeTypes.Contains(_.PropertyType.FullName)).ToList();

        var doSanitizeProperty = false;
        typeProperties.ForEach(typeProperty =>
        {
            if (doSanitizeProperty == false)
                doSanitizeProperty = ValidateSanitizeProperty(typeProperty.PropertyType, typeProperty, orgTypes);
        });

        return doSanitizeProperty;

    }

    protected override bool CanReadType(Type type)
    {
        var result = ValidateSanitizeProperty(type, null, new List<PropertyInfo>());
        return result;
    }

    private object SanitizeObject(object obj, Type modelType)
    {
        if (obj != null)
        {
            List<PropertyInfo> propertiesFlaggedForSanitization = modelType.GetProperties().Where(e => e.GetCustomAttribute<SanitizePropertyAttribute>() != null).ToList();
            if (propertiesFlaggedForSanitization.Any())
            {
                foreach (var propertyInfo in propertiesFlaggedForSanitization)
                {
                    var raw = (string)propertyInfo.GetValue(obj);
                    if (!string.IsNullOrEmpty(raw))
                    {
                        propertyInfo.SetValue(obj, CleanInput(raw));
                        //propertyInfo.SetValue(obj, AntiXssEncoder.HtmlEncode(raw, true));
                        //propertyInfo.SetValue(obj, AntiXssEncoder.UrlEncode(raw));
                    }
                }
            }
        }

        modelType.GetProperties().ToList().Where(_ => _.PropertyType.IsAnsiClass == true && !ExcludeTypes.Contains(_.PropertyType.FullName)).ToList().ForEach(property =>
        {
            try
            {
                var nObj = property.GetValue(obj);
                if (nObj != null)
                {
                    var sObj = SanitizeObject(nObj, property.PropertyType);
                    property.SetValue(obj, sObj);
                }
            }
            catch(Exception ex)
            {   
            }
        });

        return obj;
    }

    public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        if (encoding == null)
        {
            throw new ArgumentNullException(nameof(encoding));
        }

        using (var streamReader = context.ReaderFactory(context.HttpContext.Request.Body, encoding))
        {
            string jsonData = await streamReader.ReadToEndAsync();
            var nObj = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonData, context.ModelType);
            var modelType = context.ModelType;

            try
            {
                var sbj = SanitizeObject(nObj, modelType);

                return await InputFormatterResult.SuccessAsync(sbj);
            }catch (Exception ex)
            {
                return await InputFormatterResult.FailureAsync();
            }
        }
    }
}

我们在 startup.cs 类的 public void ConfigureServices(IServiceCollection services) 函数中声明,如下所示:

services.AddMvcCore(options => { options.InputFormatters.Add(new SanitizeTextInputFormatter()); })
于 2019-02-19T23:02:50.353 回答
0

DefaultModelBinder 位于MVC 控制器使用 的System.Web.ModelBinding命名空间中。

对于 WebAPI 项目,您需要实现System.Web.Http.ModelBinding.IModelBinder接口。

以下是直接取自 MSDN 站点的示例模型绑定器:

public class GeoPointModelBinder : IModelBinder
{
    // List of known locations.
    private static ConcurrentDictionary<string, GeoPoint> _locations
        = new ConcurrentDictionary<string, GeoPoint>(StringComparer.OrdinalIgnoreCase);

    static GeoPointModelBinder()
    {
        _locations["redmond"] = new GeoPoint() { Latitude = 47.67856, Longitude = -122.131 };
        _locations["paris"] = new GeoPoint() { Latitude = 48.856930, Longitude = 2.3412 };
        _locations["tokyo"] = new GeoPoint() { Latitude = 35.683208, Longitude = 139.80894 };
    }

    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType != typeof(GeoPoint))
        {
            return false;
        }

        ValueProviderResult val = bindingContext.ValueProvider.GetValue(
            bindingContext.ModelName);
        if (val == null)
        {
            return false;
        }

        string key = val.RawValue as string;
        if (key == null)
        {
            bindingContext.ModelState.AddModelError(
                bindingContext.ModelName, "Wrong value type");
            return false;
        }

        GeoPoint result;
        if (_locations.TryGetValue(key, out result) || GeoPoint.TryParse(key, out result))
        {
            bindingContext.Model = result;
            return true;
        }

        bindingContext.ModelState.AddModelError(
            bindingContext.ModelName, "Cannot convert value to Location");
        return false;
    }
}

可以在此处找到支持此示例的完整帖子: MSDN 模型绑定

于 2016-04-18T14:59:15.533 回答