我们尝试在ViewModel属性上使用[AllowHtml]修饰符,以避免YSOD:
当我们尝试提交html文本时,例如:<br>。然后我们想要在控制器操作中使用Server.HtmlEncode来防止攻击,但是当我们使用[AllowHtml]装饰属性时,它没有任何影响,如果我们在控制器操作中尝试使用[ValidateInput(false)],也没有任何效果。我们看到了一个StackOverflow帖子,说在MVC 3 RC2中,您必须添加: ModelMetadataProviders.Current = new DataAnnotationsModelMetadataProvider();到global.asax。我们也尝试过这样做,即使我们使用的是MVC 3的发行版本,而不是RC2,但也没有效果。有人知道如何解决这个问题吗?模型:客户端检测到可能有危险的Request.Form值(RequestText=<br>)。
namespace UI.Models.ViewModel
{
public class CustomerRequestSupport
{
/// <summary>
/// Gets or Sets the textual description entered by the Customer for
/// the support requested.
/// </summary>
[AllowHtml]
public string RequestText { get; set; }
}
}
控制器:
[HttpPost]
[TabsActionFilter]
public ActionResult RequestSupport(CustomerRequestSupport collection)
{
if (ModelState.IsValid)
{
Ticket ticket = new Ticket();
ticket.Requestor = LoggedInCustomer;
ticket.Summary = "General Support Ticket";
ticket.Notes = Server.HtmlEncode(collection.RequestText);
var errors = _ticketService.SubmitTicket(ticket);
if (errors.Any())
{
ModelState.AddModelError("collection",
String.Format("An error has occurred in your Request for Support: " +
"{0} Please try again later or call the help desk " +
"for immediate assistance.",
errors.Aggregate((acc, st) => acc + " " + st)));
}
else
{
TempData["FlashMessage"] = String.Format("Your request for support has been " +
"submitted, the Ticket Number is: {0}.", ticket.TicketNumber);
return AutoMapView<CustomerDetails>(View("Details", base.LoggedInCustomer));
}
}
//needed for tabs to show
ViewData.CustomerContactSet(base.LoggedInCustomer);
return View();
查看:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<UI.Models.ViewModel.CustomerRequestSupport>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Request Support
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="PageTitle" runat="server">
Request Support
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm())
{ %>
<%= Html.ValidationSummary() %>
<h2>Enter a description of the support needed</h2>
<%: Html.TextAreaFor( m => m.RequestText, 4, 90, null) %>
<input type="submit" value="Submit" />
<% } %>
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="JavaScriptContent" runat="server">
</asp:Content>