Ниже приведен фрагмент моего кода < /p>
Класс модели < /p>
// customer.cs < /p>
using CommonLayer;
namespace Models
{
public class Customer
{
public int Id { get; set; }
[MyAntiXss]
public string Name { get; set; }
}
}
< /code>
Я хочу дезинфицировать значение в поле «Имя» класса модели, как показано ниже < /p>
// cutstomdomledbinder.cs < /p>
// 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().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);
}
}
}
< /code>
Я изменил «defaultbinder» на мой 'cutstomdelbinder', как ниже < /p>
// global.asax.cs < /p>
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();
}
}
}
< /code>
Я написал класс контроллера, как ниже < /p>
// customercontroller.cs < /p>
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);
}
}
}
< /code>
Когда я вызову приведенный выше метод класса контроллера «Post '», как ниже, он дает вызов методу «post» класса контроллера, как и ожидалось. Но он не вызывает метод «bindproperty» в моем классе «cutstomdelbinder». < /P>
// Program.cs < /p>
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 = "
Anivesh" };
HttpContent content = new ObjectContent(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().Result;
return expected == result;
}
else
return false;
}
}
}
< /code>
Пожалуйста, дайте мне знать правильный способ использования «данных данных», чтобы я мог дезинфицировать входные данные в общем месте, прежде чем получать вызовы в контроллерах. < /p>
Подробнее здесь: https://stackoverflow.com/questions/325 ... xss-attack
Как дезинфицировать входные данные в веб -API с использованием атаки против XSS ⇐ C#
Место общения программистов C#
1750390988
Anonymous
Ниже приведен фрагмент моего кода < /p>
Класс модели < /p>
// customer.cs < /p>
using CommonLayer;
namespace Models
{
public class Customer
{
public int Id { get; set; }
[MyAntiXss]
public string Name { get; set; }
}
}
< /code>
Я хочу дезинфицировать значение в поле «Имя» класса модели, как показано ниже < /p>
// cutstomdomledbinder.cs < /p>
// 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().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);
}
}
}
< /code>
Я изменил «defaultbinder» на мой 'cutstomdelbinder', как ниже < /p>
// global.asax.cs < /p>
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();
}
}
}
< /code>
Я написал класс контроллера, как ниже < /p>
// customercontroller.cs < /p>
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);
}
}
}
< /code>
Когда я вызову приведенный выше метод класса контроллера «Post '», как ниже, он дает вызов методу «post» класса контроллера, как и ожидалось. Но он не вызывает метод «bindproperty» в моем классе «cutstomdelbinder». < /P>
// Program.cs < /p>
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 = "
Anivesh" };
HttpContent content = new ObjectContent(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().Result;
return expected == result;
}
else
return false;
}
}
}
< /code>
Пожалуйста, дайте мне знать правильный способ использования «данных данных», чтобы я мог дезинфицировать входные данные в общем месте, прежде чем получать вызовы в контроллерах. < /p>
Подробнее здесь: [url]https://stackoverflow.com/questions/32599961/how-to-sanitize-input-data-in-web-api-using-anti-xss-attack[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия