我有一个MVC操作过滤器,用于验证我的模型,它在不同版本的IIS上给出了不同的响应。以下是操作过滤器的代码。
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var viewData = filterContext.Controller.ViewData;
var modelStateErrors = filterContext.Controller.ViewData.ModelState.Keys.SelectMany(key => filterContext.Controller.ViewData.ModelState[key].Errors);
string errorMessage;
if (modelStateErrors.Count() > 0)
{
ModelError error = modelStateErrors.FirstOrDefault();
if (error.ErrorMessage.IsNotNullOrEmpty())
{
errorMessage = error.ErrorMessage;
}
else if (error.Exception != null)
{
errorMessage = error.Exception.Message;
}
else
{
errorMessage = Messages.UNKNOWN_VALIDATION_ERROR;
}
}
else
{
errorMessage = Messages.UNKNOWN_VALIDATION_ERROR;
}
if (!viewData.ModelState.IsValid)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
filterContext.Result = new ContentResult { Content = errorMessage, ContentType = "text/plain" };
}
else
{
var controller = filterContext.Controller as WMSControllerBase;
if (controller != null)
{
controller.DisplayWarningMessage(errorMessage);
}
foreach (var param in filterContext.ActionParameters)
{
if (param.Key.ToLower() == "model" || param.Value is ViewModelBase)
{
viewData.Model = param.Value;
break;
}
}
if (viewData.Model is ViewModelBase)
{
(viewData.Model as ViewModelBase).RebuildModel();
}
filterContext.Result = new ViewResult
{
ViewData = viewData
};
}
}
base.OnActionExecuting(filterContext);
}
}
在IIS 7.0服务器上,操作过滤器按预期工作,并将为AJAX调用生成如下响应。
HTTP/1.1 400 Bad Request
Cache-Control: private
Content-Type: text/plain; charset=utf-8
Server: Microsoft-IIS/7.0
X-AspNetMvc-Version: 4.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 08 Oct 2013 21:40:36 GMT
Content-Length: 47
The error message I want the end user to see.
但是,在IIS 7.5或更高版本上运行时,我会收到如下响应。显然,IIS或MVC决定用“错误请求”替换我的响应主体,并将类型设置为text / html。想知道这里发生了什么,为什么会像这样修改响应呢?
HTTP/1.1 400 Bad Request
Cache-Control: private
Content-Type: text/html
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 4.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 08 Oct 2013 21:50:02 GMT
Content-Length: 11
Bad Request