我目前正在研究.Net Core 2.2异常处理方案。我正在使用UseDeveloperExceptionPage()
来在开发模式下显示异常信息。但是当我对一种控制器方法进行Ajax处理时,如果应用程序抛出运行时异常。我没有与Exception Details一起显示,UseDeveloperExceptionPage
而是在Ajax error
function()中得到响应。任何人都可以解释为什么未显示“开发人员例外”页面的原因。并且请向我解释如何在ajax调用期间显示“开发人员异常”页面以及异常详细信息。
以下是Configure()
我的Startup.cs
文件中的
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseStatusCodePagesWithReExecute("/Error/{0}");
}
else
{
app.UseExceptionHandler("/Exception");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
//app.UseAuthentication();
app.UseSession();
//app.UseCookiePolicy();
app.UseMiddleware<AuthenticationMiddleware>();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Account}/{action=Index}/{id?}");
});
}
Java脚本
$.ajax({
url: "@Url.Action("Index", "Home")",
dataType: "json",
type: "POST",
Async: true,
success: function(result) {
// Do Something
},
error: function() {
alert("Oops!! Error Occured");
}
});
家庭控制器
public IActionResult Index()
{
throw new Exception();
return View(viewTransactionsBatchSearch);
}
您可以这样获取异常信息:
$.ajax({
url: "@Url.Action("Index", "Home")",
dataType: "json",
type: "POST",
Async: true,
success: function (result) {
// Do Something
},
error: function (result) {
//do something with the responseText which contains the Body of the response
alert(result.responseText);
}
});
控制器不知道您是否使用AJAX调用了它...它只是查看Http请求。您可以通过在错误函数中添加参数来检查Http响应。
例如,您可以检查responseText属性以获取异常信息。
例如,您可以将内容设置为div或其他显示元素。
同样因为您的AJAX请求的dataType设置为“ json”,所以reponseText将仅包含异常信息和标头。
如果将dataType设置为“ html”,您将获得FULL Developer Exception Page的html,然后可以使用它进行处理。
这里有一些有关如何处理responseText的示例。
示例1当dataType:“ html”:
$.ajax({
url: "@Url.Action("Index", "Home")",
dataType: "html",
type: "POST",
Async: true,
success: function (result) {
// Do Something
},
error: function (result) {
document.open();
document.write(result.responseText);//this will replace the current page with the developer exception page
document.close();
}
});
例2,当dataType:“ json”: 这是不同的,因为您请求了JSON,因此服务器不会返回完整的HTML文档。
这个看起来并不“漂亮”,但是它具有所有异常信息。
$.ajax({
url: "@Url.Action("Index", "Home")",
dataType: "json",
type: "POST",
Async: true,
success: function (result) {
// Do Something
},
error: function (result) {
document.body.innerHTML = result.responseText;
}
});
亲爱的朋友,我同意你)
非常感谢你。是否有可能知道运行javascript的环境类型。就像我们
if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); }
在startup.cs中一样@Vijay不客气。如果这可以解决您的问题,请标记为答案。