如何将ASP.NET MVC3 JsonResult
方法中的自定义错误信息传递给error
(success
或者complete
,如果需要)函数jQuery.ajax()
?理想情况下,我希望能够:
这是我的代码的基本版本:
public JsonResult DoStuff(string argString)
{
string errorInfo = "";
try
{
DoOtherStuff(argString);
}
catch(Exception e)
{
errorInfo = "Failed to call DoOtherStuff()";
//Edit HTTP Response here to include 'errorInfo' ?
throw e;
}
return Json(true);
}
Run Code Online (Sandbox Code Playgroud)
$.ajax({
type: "POST",
url: "../MyController/DoStuff",
data: {argString: "arg string"},
dataType: "json",
traditional: true,
success: function(data, statusCode, xhr){
if (data === true)
//Success handling
else
//Error handling here? …
Run Code Online (Sandbox Code Playgroud) 我希望将所有401错误重定向到自定义错误页面.我最初在web.config中设置了以下条目.
<customErrors defaultRedirect="ErrorPage.aspx" mode="On">
<error statusCode="401" redirect="~/Views/Shared/AccessDenied.aspx" />
</customErrors>
Run Code Online (Sandbox Code Playgroud)
使用IIS Express时,我收到了IIS Express 401错误页面.
如果我不使用IIS Express,则返回空白页面.使用Google Chrome的"网络"标签检查响应,我看到当页面为空白时,标题中会返回401状态
到目前为止我尝试使用的是这个SO答案中的建议,因为我使用的是IIS Express,但无济于事.我尝试过使用组合<custom errors>
而<httpErrors>
没有运气 - 标准错误或空白页仍然显示.
该httpErrors
部分看起来像这样的基础上,瞬间链接从上面的SO问题(我还发现了另一种非常有前途的答案却没有运气-空白响应)
<system.webServer>
<httpErrors errorMode="DetailedLocalOnly" existingResponse="PassThrough" >
<remove statusCode="401" />
<error statusCode="401" path="/Views/Shared/AccessDenied.htm" />
</httpErrors>
<!--
<httpErrors errorMode="Custom"
existingResponse="PassThrough"
defaultResponseMode="ExecuteURL">
<remove statusCode="401" />
<error statusCode="401" path="~/Views/Shared/AccessDenied.htm"
responseMode="File" />
</httpErrors>
-->
</system.webServer>
Run Code Online (Sandbox Code Playgroud)
我甚至已经修改了applicationhost.config
文件,并修改<httpErrors lockAttributes="allowAbsolutePathsWhenDelegated,defaultPath">
,以<httpErrors lockAttributes="allowAbsolutePathsWhenDelegated">
基于从信息iis.net.在我努力的过程中,我也设法偶然发现了另一个SO问题中描述的这个错误.
如何在Asp.Net Mvc …
error-handling http-error custom-error-pages iis-express asp.net-mvc-3
我在我的共享主机上部署的ASP.NET MVC应用程序上遇到自定义错误问题.我创建了一个ErrorController并将以下代码添加到Global.asax以捕获未处理的异常,记录它们,然后将控制转移到ErrorController以显示自定义错误.此代码取自此处:
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
Response.Clear();
HttpException httpEx = ex as HttpException;
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
if (httpEx == null)
{
routeData.Values.Add("action", "Index");
}
else
{
switch (httpEx.GetHttpCode())
{
case 404:
routeData.Values.Add("action", "HttpError404");
break;
case 500:
routeData.Values.Add("action", "HttpError500");
break;
case 503:
routeData.Values.Add("action", "HttpError503");
break;
default:
routeData.Values.Add("action", "Index");
break;
}
}
ExceptionLogger.LogException(ex); // <- This is working. Errors get logged
routeData.Values.Add("error", ex);
Server.ClearError();
IController controller = new ErrorController(); …
Run Code Online (Sandbox Code Playgroud) 我试图在用户上传超过限制的文件时显示错误页面(请参阅捕获"超出最大请求长度")
在global.asax我想重定向到一个控制器动作,所以这样的东西,但它不起作用?:
private void Application_Error(object sender, EventArgs e)
{
if (GlobalHelper.IsMaxRequestExceededEexception(this.Server.GetLastError()))
{
this.Server.ClearError();
return RedirectToAction("Home","Errorpage");
}
}
Run Code Online (Sandbox Code Playgroud) 我有一个自定义HandleError
属性来处理MVC管道上的错误; 我有一个protected void Application_Error(object sender, EventArgs e)
方法Global.asax
来处理来自管道外部的错误.
我遇到过一个我不知道可能的情景; 在实现DI时,存在对a的依赖性connectionString
,该依赖性取自应用程序配置文件.
由于连接字符串尚不存在,因此在创建控制器时会出错,这通常会使Application_Error
处理程序触发,并呈现正确的错误页面(通过将部分视图呈现为字符串并将其作为响应发送,以防万一这失败了它只是写了"致命异常."的回应.
除了在这种情况下,我得到了虚假的默认ASP.NET"运行时错误"黄色死亡屏幕.告诉我:
运行时错误
说明:服务器上发生应用程序错误.此应用程序的当前自定义错误设置可防止查看应用程序错误的详细信息.
详细信息:要在本地服务器计算机上查看此特定错误消息的详细信息,请在位于当前Web应用程序根目录中的"web.config"配置文件中创建标记.然后,此标记应将其"mode"属性设置为"RemoteOnly".要使详细信息可在远程计算机上查看,请将"mode"设置为"Off".
我没有defaultRedirect
设置customErrors
,也没有设置Off
,因为我不想重定向,而是在用户所在的同一页面上呈现错误,避免了不必要的重定向.
我该如何处理这样的场景?甚至是什么原因导致它以这种方式运行而不像控制器之外的任何其他错误?
我意识到它不太可能经常发生,但我希望能够阻止YSOD(部分原因是因为我想隐藏我正在使用的技术,但主要是因为它不是很漂亮,也不是用户友好的)
我甚至尝试为UnhandledExceptions注册一个处理程序,但它也没有触发.
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
Run Code Online (Sandbox Code Playgroud)
最终产生这个的代码是:
return ConfigurationManager.ConnectionStrings[key].ConnectionString;
,这里ConnectionStrings[key]
是null
.
更新
这是应用程序错误的处理方式:
protected void Application_Error(object sender, EventArgs e)
{
this.HandleApplicationError(new ResourceController());
}
public static void HandleApplicationError(this HttpApplication application, BaseController controller)
{
if (application == null)
{
throw new ArgumentNullException("application");
}
if (controller == null)
{ …
Run Code Online (Sandbox Code Playgroud) 我们目前正在将我们的Web表单系统重新开发为Web API和MVC(这对我们来说是新技术)到目前为止,一切似乎都没问题,但我们正在努力将Web API应用程序中的错误发送回MVC应用程序.我们意识到我们需要捕获任何异常,并将这些异常转换为HTTP响应
Web API Product控制器如下所示:
public HttpResponseMessage GetProducts()
{
BAProduct c = new BAProduct();
var d = c.GetProducts();
if (d == null)
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "This is a custom error message");
else
return Request.CreateResponse(HttpStatusCode.OK, d);
}
Run Code Online (Sandbox Code Playgroud)
MVC应用程序将通过以下代码调用Web API: -
public T Get<T>()
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(Config.API_BaseSite);
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/myapplicaton/products").Result;
response.EnsureSuccessStatusCode();
T res = response.Content.ReadAsAsync<T>().Result;
return (T)res;
}
}
Run Code Online (Sandbox Code Playgroud)
我们想要实现的是当从MVC应用程序中的Web API收到HTTP错误时,用户被重定向到自定义错误页面,或者在当前视图中显示自定义错误消息(取决于错误).我们遇到的问题是: -
如何访问我们发回的自定义错误消息?(从示例代码中这将是"这是一个自定义错误消息",我们已经通过res中的每个属性并且看不到此消息)
根据状态代码,我们如何捕获并将用户重定向到各个错误页面,即404页面,500页面,并显示已发回的自定义响应消息.我们一直沿着global.asax路线走下去
protected void Application_Error(object sender, EventArgs e)
{ …
Run Code Online (Sandbox Code Playgroud)我试图在一个库存样本ASP.NET MVC3网站上有2个自定义错误页面.
Darin Dimitrov在这里有一个很好的答案,但它并不适合我所有的测试条件.
然后广泛流行如何在ASP.NET MVC中正确处理404?发布..但这只是触及404错误.
有人可以解释一下
web.config
设置要做这个非常简单的事情:(
接受这个答案的场景:
ErrorController
)......并为测试路线......
/Home/Index
- >显示索引页面/Home
- >显示索引页面/
- >显示索引页面/Home/About
- >显示关于页面/asdasd/asdsad/asdas/asddasd/adsad
- > 404/adsa/asda/asd/asd/asd/asd
- > 404/asdsadasda
- > 404然后将其添加到HomeController.cs
班级..
public ActionResult ThrowException()
{
throw new NotImplementedException();
}
Run Code Online (Sandbox Code Playgroud)
现在 ..
/home/throwexception
- > 500错误干杯:)
顺便说一下,当使用股票标准new ASP.NET MVC3 …
如何更改ASP.NET Web API永远不会返回text/html
404响应?我宁愿它用ExceptionMessage
或发回XML/JSON Message
.从IMO返回HTML是没有意义的.
只是为了澄清,这适用于URL真正无效的情况.
另一个问题是我在同一个项目中托管MVC和Web API,所以我需要做出不同的回应.我猜这将取决于URL是否以"api"开头.
我在我的网站上设置了自定义错误页面
<customErrors mode="RemoteOnly" defaultRedirect="~/Error">
<error statusCode="500" redirect="~/Error/InternalError"/>
<error statusCode="404" redirect="~/Error/FileNotFound"/>
<error statusCode="403" redirect="~/Error/AccessDenied"/>
</customErrors>
Run Code Online (Sandbox Code Playgroud)
但是,在供应商网站上还有另一个区域,当供应商区域发生错误时,重定向将转到供应商/错误/ _.由于我这里没有任何错误页面,网站似乎挂起从不显示错误页面.如何在不必将错误页面复制到供应商区域的情况下解决此问题?
我有一个问题,因为HTTP错误404.0 - 未找到.我打开了
<customErrors mode="On" defaultRedirect="~/Error/General">
<error statusCode="404" redirect="~/Error/HttpError404" />
<error statusCode="500" redirect="~/Error/HttpError500" />
</customErrors>
Run Code Online (Sandbox Code Playgroud)
在Web.Config中.但问题仍然存在.我也试过这个解决方案(但它永远不会到达方法):
protected void Application_Error()
{
var exception = Server.GetLastError();
var httpException = exception as HttpException;
Response.Clear();
Server.ClearError();
var routeData = new RouteData();
routeData.Values["controller"] = "Errors";
routeData.Values["action"] = "General";
routeData.Values["exception"] = exception;
Response.StatusCode = 500;
if (httpException != null)
{
Response.StatusCode = httpException.GetHttpCode();
switch (Response.StatusCode)
{
case 403:
routeData.Values["action"] = "HttpError404";
break;
case 404:
routeData.Values["action"] = "HttpError404";
break;
}
}
IController errorsController = new ErrorController();
var …
Run Code Online (Sandbox Code Playgroud) c# ×4
asp.net-mvc ×3
.net ×1
ajax ×1
c#-4.0 ×1
global-asax ×1
http-error ×1
iis-8 ×1
iis-express ×1
jquery ×1