這是一個ASP.Net MVC 5
項目AllowHtml作品上創建,但不是在編輯ASP.Net MVC 5
我有一個簡單的模型,其它的一個屬性允許HTML
輸入:
public class FooModel {
//other properties
[AllowHtml]
public string BarField { get; set; }
}
和控制器它使用模型如下所示:
[OutputCache(NoStore = true, Duration = 0, Location = OutputCacheLocation.None)]
public class FooController : Controller {
//some other codes...
// GET: Foo/Create
public ActionResult Create(int? id, int number = 0) {
//some code
}
// POST: Foo/Create
[HttpPost]
public ActionResult Create(FooModel fooModel) {
//some code
}
// GET: Foo/Edit/5
public ActionResult Edit(int? id, int number = 0) {
//some code
}
// POST: Foo/Edit/5
[HttpPost]
public ActionResult Edit(FooModel model, FormCollection collection) {
//some code
}
}
在閱讀一些支柱在SO:
我知道,必須進行以下工作來確保AllowHtml
屬性的工作:
- 使用
<httpRuntime requestValidationMode="2.0" />
在web.config - 清理模型所在控制器的緩存通過並用
[OutputCache(NoStore = true, Duration = 0, Location = OutputCacheLocation.None)]
因此,我在web.config我<system.web>
以下完整的元素:
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.6" />
<httpRuntime targetFramework="4.5" requestValidationMode="2.0" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
</system.web>
而且,正如你所看到的,我也已經把頂部的OutputCache
屬性控制器:
[OutputCache(NoStore = true, Duration = 0, Location = OutputCacheLocation.None)]
現在,這都非常好,Create
行動(即我可以在BarField
和後插入HTML元素被接受並且Action被調用而沒有問題)。
但是,當我做Edit
行動,行動甚至沒有叫和錯誤:
A potentially dangerous Request.Form value was detected from the client (BarField="...words here <i>and also here</i><...").
Description: ASP.NET has detected data in the request that is potentially dangerous because it might include HTML markup or script. The data might represent an attempt to compromise the security of your application, such as a cross-site scripting attack. If this type of input is appropriate in your application, you can include code in a web page to explicitly allow it. For more information, see http://go.microsoft.com/fwlink/?LinkID=212874 .
顯示在頁面上。這是爲什麼?
從Edit()方法中刪除'FormCollection集合'參數 –
@StephenMuecke就是這樣!有用!謝謝,Pal ...:D但是爲什麼'FormCollection'妨礙表單提交? – Ian
由於您將張貼的值綁定到您的模型(並且'[AllowHtml]'處理'BarField'屬性上的請求),但是您也綁定到沒有應用該屬性的FormCollection(NameValueCollection) (雖然你可以使用'[ValidateInput(false)]'但它沒有理由將相同的值綁定到2個不同的模型,並且沒有理由在MVC中使用'FormCollection' –