我正在使用C#和Twitter Bootstrap構建我的第一個網站,並且在發現HTTP標題發送後「服務器無法追加標頭」錯誤需要在return View(model)
之後顯示驗證問題和TempData["ErrorMessage"]
。具體的錯誤發生在html行@Html.AntiForgeryToken()
。如果消息已設置並返回驗證外的View,則不會發生此錯誤。在使用AntiForgeryToken發送HTTP標頭之後,服務器無法追加標題
我試過了:將return View(model)
更改爲RedirectToAction ("Action", new { id = model.id })
和Redirect ("/Controller/Action/" + model.id.ToString())
,如果該行不在驗證範圍內,則工作,但在條件驗證內失敗;在Application_start
內將AntiForgeryConfig.SuppressXFrameOptionsHeader
設置爲true;並在設置TempData並返回到視圖之前調用HttpContext.Response.Clear()
。我還沒有嘗試操作cookie,因爲我不確定如何專門處理反僞造令牌。
我想要做的就是返回視圖,在頁面上顯示錯誤/驗證消息,而不是彈出消息框,上述方法都不起作用。有誰知道爲什麼這個目標在驗證之外,但不在裏面?提前謝謝了!
//Any return and message works correctly if done here
try
{
//Various other validations using values pulled from database
if (model.NewString.Length > 50 || model.NewString.Length < 7)
{
//This throws the error
TempData["ErrorMessage"] = "Please enter a value of valid length.";
return View(model);
}
}
catch
{
TempData["ErrorMessage"] = "There has been an error.";
return RedirectToAction("Index");
}
編輯:這裏是行動的,是每Amit的請求。
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize (Roles = "Administrator, Owner, Director, Manager")]
[RequireSsl]
public ActionResult CreateCustomer (CreateCustomerModel model)
{
dbEntities db = new dbEntities();
var CurrentBusinessID = 0;
var CurrentPosition = "";
var CurrentUserID = 0;
try
{
if (Session["CurrentUserID"] != null)
{
CurrentUserID = (int)Session["CurrentUserID"];
CurrentBusinessID = (int)Session["CurrentBusinessInfoID"];
CurrentPosition = (string)Session["CurrentPosition"];
}
else
{
Response.Redirect("/Account/Logon");
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
Response.Redirect("/Account/Logon");
}
try
{
var account = db.uspGetAccount(model.AccountID).FirstOrDefault();
AccountsModel thisAccount = new AccountsModel()
{
AccountID = model.AccountID,
BusinessID = account.BusinessID
};
if (thisAccount.BusinessID != CurrentBusinessID)
{
Response.Redirect("/Home/Dashboard");
}
if (model.Name == null || model.Name == "")
{
TempData["ErrorMessage"] = "Please enter a name.";
return View(model);
}
if (model.NewString.Length > 50 || model.NewString.Length < 7)
{
//This throws the error
TempData["ErrorMessage"] = "Please enter a value of valid length.";
return View(model);
}
db.AddCustomer(model.Name, model.NewString);
}
catch
{
TempData["ErrorMessage"] = "There has been an error.";
return RedirectToAction("Index");
}
return RedirectToAction("Accounts");
}
https://stackoverflow.com/questions/34270192/server-cannot-append-header-after-http-headers-have-been-sent-exception-at-html – Amit
@Amit - 謝謝你鏈接,但我實際上實現了答案,它不起作用。具體來說,當我在我的回答中提到對RedirectToAction和Redirect的更改以及SuppressXFrameOptionsHeader時,這是我所關注的帖子。 – jle
你可以照原樣粘貼這個方法的控制器代碼嗎?如果您的Model.NewString的if語句不起作用,則不會有return語句。此外,您可以在任何return語句之前嘗試Response.ClearHeaders()。 – Amit