下面是我的代码片段
模型类
// 客户.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”的正确方法,以便我可以在控制器中接收呼叫之前在一个公共位置清理输入数据。