在这篇文章中,我们将为您详细介绍C#MVC全局错误Application_Error中处理的内容,并且讨论关于包括Ajax请求的相关问题。此外,我们还会涉及一些关于.net–Application_E
在这篇文章中,我们将为您详细介绍C# MVC 全局错误Application_Error中处理的内容,并且讨论关于包括Ajax请求的相关问题。此外,我们还会涉及一些关于.net – Application_Error不会触发?、Ajax的text/plain、application/x-www-form-urlencoded和application/json、Application application_1512618719369_147804 failed 2 times due to ApplicationMaster for attempt app、application error 用php实现像JSP,ASP里Application那样的全局变量的知识,以帮助您更全面地了解这个主题。
本文目录一览:- C# MVC 全局错误Application_Error中处理(包括Ajax请求)(mvc 全局异常处理)
- .net – Application_Error不会触发?
- Ajax的text/plain、application/x-www-form-urlencoded和application/json
- Application application_1512618719369_147804 failed 2 times due to ApplicationMaster for attempt app
- application error 用php实现像JSP,ASP里Application那样的全局变量
C# MVC 全局错误Application_Error中处理(包括Ajax请求)(mvc 全局异常处理)
在MVC的Global.asax Application_Error 中处理全局错误。
如果在未到创建请求对象时报错,此时 Context.Handler == null 。
判断为Ajax请求时,我们返回Json对象字符串。不是Ajax请求时,转到错误显示页面。
/// <summary>
/// 全局错误
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
LogHelper.Error(ex); // 记录错误日志(NLog 挺好用的(* ̄︶ ̄))
if (Context.Handler == null)
{
return;
}
if (new HttpRequestWrapper(Request).IsAjaxRequest())
{
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write("{\"state\":\"0\",\"msg\":\"" + ex.Message + "\"}");
Response.Flush();
Response.End();
}
else
{
// 方案一 重定向到错误页面,带上简单的错误信息
//string errurl = "/Error/Error?msg=" + ex.Message;
//Response.Redirect(errurl, true);
// 方案二 带上错误对象,转到错误页
Response.Clear();
RouteData routeData = new RouteData();
routeData.Values.Add("Controller", "Error"); // 已有的错误控制器
routeData.Values.Add("Action", "Error"); // 自定义的错误页面
Server.ClearError();
ErrorController controller = new ErrorController();
HandleErrorInfo handleErrorInfo = new HandleErrorInfo(ex, "Error", "Error");
controller.ViewData.Model = handleErrorInfo;
((IController)controller).Execute(new RequestContext(new HttpContextWrapper(((MvcApplication)sender).Context), routeData));
}
}
其中方案二的对象用法,与默认的错误页(即 /Shared/Error.cshtml)一样。当我们不对错误进行任何处理时,在web.config中可配置错误页到 /Shared/Error.cshtml。
Error.cshtml的代码:
@model System.Web.Mvc.HandleErrorInfo
@{
ViewBag.Title = "系统错误";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h3 class="text-danger">系统错误</h3>
@if (Model != null)
{
<span class="text-warning">@(Model.Exception.Message)</span>
}
else
{
<span class="text-warning">处理请求时出错。</span>
}
方案二的Action的代码:
public ActionResult Error()
{
return View();
}
相关配置影响:
<!--开启会导致异常不走Application_Error,直接寻Error-->
<!--<customErrors mode="On" defaultRedirect="~/Error.cshtml" />-->
.net – Application_Error不会触发?
protected void Page_Load(object sender,EventArgs e) { throw new Exception("test exception"); }
在Global.asax.cs中:
protected void Application_Error(object sender,EventArgs e) { // Code that runs when an unhandled error occurs if (Server.GetLastError() is HttpUnhandledException) Server.Transfer("ErrUnkNown.aspx"); }
但是从不调用Application_Error事件处理程序.相反,我得到一个运行时错误页面.
在抛出异常后,我需要做什么才能调用Application_Error?
解决方法
您是否通过调试应用程序进行了检查?
实际上你缺少Server.ClearError()所以异常被传递给asp.net但你应该在这里压制它,因为你自己处理它.
protected void Application_Error(object sender,EventArgs e) { // Code that runs when an unhandled error occurs if (Server.GetLastError() is HttpUnhandledException) { // suppressing the error so it should not pass to asp.net Server.ClearError(); Server.Transfer("ErrUnkNown.aspx"); } }
Ajax的text/plain、application/x-www-form-urlencoded和application/json
Ajax的text/plain、application/x-www-form-urlencoded和application/json
HTTP请求中,如果是get请求,那么表单参数以name=value&name1=value1的形式附到url的后面,如果是post请求,那么表单参数是在请求体中,也是以name=value&name1=value1的形式在请求体中。通过chrome的开发者工具可以看到如下(这里是可读的形式,不是真正的HTTP请求协议的请求格式):
get请求:
[plain] view plain copy
- RequestURL:http://127.0.0.1:8080/test/test.do?name=mikan&address=street
- Request Method:GET
- Status Code:200 OK
- Request Headers
- Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
- Accept-Encoding:gzip,deflate,sdch
- Accept-Language:zh-CN,zh;q=0.8,en;q=0.6
- AlexaToolbar-ALX_NS_PH:AlexaToolbar/alxg-3.2
- Connection:keep-alive
- Cookie:JSESSIONID=74AC93F9F572980B6FC10474CD8EDD8D
- Host:127.0.0.1:8080
- Referer:http://127.0.0.1:8080/test/index.jsp
- User-Agent:Mozilla/5.0 (Windows NT 6.1)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.149 Safari/537.36
- Query String Parameters
- name:mikan
- address:street
- Response Headers
- Content-Length:2
- Date:Sun, 11 May 2014 10:42:38 GMT
- Server:Apache-Coyote/1.1
Post请求:
[plain] view plain copy
- RequestURL:http://127.0.0.1:8080/test/test.do
- Request Method:POST
- Status Code:200 OK
- Request Headers
- Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
- Accept-Encoding:gzip,deflate,sdch
- Accept-Language:zh-CN,zh;q=0.8,en;q=0.6
- AlexaToolbar-ALX_NS_PH:AlexaToolbar/alxg-3.2
- Cache-Control:max-age=0
- Connection:keep-alive
- Content-Length:25
- Content-Type:application/x-www-form-urlencoded
- Cookie:JSESSIONID=74AC93F9F572980B6FC10474CD8EDD8D
- Host:127.0.0.1:8080
- Origin:http://127.0.0.1:8080
- Referer:http://127.0.0.1:8080/test/index.jsp
- User-Agent:Mozilla/5.0 (Windows NT 6.1)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.149 Safari/537.36
- Form Data
- name:mikan
- address:street
- Response Headers
- Content-Length:2
- Date:Sun, 11 May 2014 11:05:33 GMT
- Server:Apache-Coyote/1.1
这里要注意post请求的Content-Type为application/x-www-form-urlencoded,参数是在请求体中,即上面请求中的Form Data。
在servlet中,可以通过request.getParameter(name)的形式来获取表单参数。
而如果使用原生AJAX POST请求的话:
[javascript] view plain copy
- function getXMLHttpRequest() {
- var xhr;
- if(window.ActiveXObject) {
- xhr= new ActiveXObject("Microsoft.XMLHTTP");
- }else if (window.XMLHttpRequest) {
- xhr= new XMLHttpRequest();
- }else {
- xhr= null;
- }
- return xhr;
- }
- function save() {
- var xhr = getXMLHttpRequest();
- xhr.open("post","http://127.0.0.1:8080/test/test.do");
- var data = "name=mikan&address=street...";
- xhr.send(data);
- xhr.onreadystatechange= function() {
- if(xhr.readyState == 4 && xhr.status == 200) {
- alert("returned:"+ xhr.responseText);
- }
- };
- }
通过chrome的开发者工具看到请求头如下:
[plain] view plain copy
- RequestURL:http://127.0.0.1:8080/test/test.do
- Request Method:POST
- Status Code:200 OK
- Request Headers
- Accept:*/*
- Accept-Encoding:gzip,deflate,sdch
- Accept-Language:zh-CN,zh;q=0.8,en;q=0.6
- AlexaToolbar-ALX_NS_PH:AlexaToolbar/alxg-3.2
- Connection:keep-alive
- Content-Length:28
- Content-Type:text/plain;charset=UTF-8
- Cookie:JSESSIONID=C40C7823648E952E7C6F7D2E687A0A89
- Host:127.0.0.1:8080
- Origin:http://127.0.0.1:8080
- Referer:http://127.0.0.1:8080/test/index.jsp
- User-Agent:Mozilla/5.0 (Windows NT 6.1)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.149 Safari/537.36
- Request Payload
- name=mikan&address=street
- Response Headers
- Content-Length:2
- Date:Sun, 11 May 2014 11:49:23 GMT
- Server:Apache-Coyote/1.1
注意请求的Content-Type为text/plain;charset=UTF-8,而请求表单参数在RequestPayload中。
那么servlet中通过request.getParameter(name)却是空。为什么呢?而这样的参数又该怎么样获取呢?
为了搞明白这个问题,查了些资料,也看了Tomcat7.0.53关于请求参数处理的源码,终于搞明白了是怎么回事。
HTTP POST表单请求提交时,使用的Content-Type是application/x-www-form-urlencoded,而使用原生AJAX的POST请求如果不指定请求头RequestHeader,默认使用的Content-Type是text/plain;charset=UTF-8。
由于Tomcat对于Content-Type multipart/form-data(文件上传)和application/x-www-form-urlencoded(POST请求)做了“特殊处理”。下面来看看相关的处理代码。
Tomcat的HttpServletRequest类的实现类为org.apache.catalina.connector.Request(实际上是org.apache.coyote.Request),而它对处理请求参数的方法为protected void parseParameters(),这个方法中对Content-Type multipart/form-data(文件上传)和application/x-www-form-urlencoded(POST请求)的处理代码如下:
[java] view plain copy
- protectedvoid parseParameters() {
- //省略部分代码......
- parameters.handleQueryParameters();// 这里是处理url中的参数
- //省略部分代码......
- if ("multipart/form-data".equals(contentType)) { // 这里是处理文件上传请求
- parseParts();
- success = true;
- return;
- }
- if(!("application/x-www-form-urlencoded".equals(contentType))) {// 这里如果是非POST请求直接返回,不再进行处理
- success = true;
- return;
- }
- //下面的代码才是处理POST请求参数
- //省略部分代码......
- try {
- if (readPostBody(formData, len)!= len) { // 读取请求体数据
- return;
- }
- } catch (IOException e) {
- // Client disconnect
- if(context.getLogger().isDebugEnabled()) {
- context.getLogger().debug(
- sm.getString("coyoteRequest.parseParameters"),e);
- }
- return;
- }
- parameters.processParameters(formData, 0, len); // 处理POST请求参数,把它放到requestparameter map中(即request.getParameterMap获取到的Map,request.getParameter(name)也是从这个Map中获取的)
- // 省略部分代码......
- }
- protected int readPostBody(byte body[], int len)
- throws IOException {
- int offset = 0;
- do {
- int inputLen = getStream().read(body, offset, len - offset);
- if (inputLen <= 0) {
- return offset;
- }
- offset += inputLen;
- } while ((len - offset) > 0);
- return len;
- }
从上面代码可以看出,Content-Type不是application/x-www-form-urlencoded的POST请求是不会读取请求体数据和进行相应的参数处理的,即不会解析表单数据来放到request parameter map中。所以通过request.getParameter(name)是获取不到的。
那么这样提交的参数我们该怎么获取呢?
当然是使用最原始的方式,读取输入流来获取了,如下所示:
[java] view plain copy
- privateString getRequestPayload(HttpServletRequest req) {
- StringBuildersb = new StringBuilder();
- try(BufferedReaderreader = req.getReader();) {
- char[]buff = new char[1024];
- intlen;
- while((len = reader.read(buff)) != -1) {
- sb.append(buff,0, len);
- }
- }catch (IOException e) {
- e.printStackTrace();
- }
- returnsb.toString();
- }
当然,设置了application/x-www-form-urlencoded的POST请求也可以通过这种方式来获取。
所以,在使用原生AJAX POST请求时,需要明确设置Request Header,即:
[javascript] view plain copy
- xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
另外,如果使用jQuery,我使用1.11.0这个版本来测试,$.ajax post请求是不需要明确设置这个请求头的,其他版本的本人没有亲自测试过。相信在1.11.0之后的版本也是不需要设置的。不过之前有的就不一定了。这个没有测试过。
2015-04-17后记:
最近在看书时才真正搞明白,服务器为什么会对表单提交和文件上传做特殊处理,因为表单提交数据是名值对的方式,且Content-Type为application/x-www-form-urlencoded,而文件上传服务器需要特殊处理,普通的post请求(Content-Type不是application/x-www-form-urlencoded)数据格式不固定,不一定是名值对的方式,所以服务器无法知道具体的处理方式,所以只能通过获取原始数据流的方式来进行解析。
jquery在执行post请求时,会设置Content-Type为application/x-www-form-urlencoded,所以服务器能够正确解析,而使用原生ajax请求时,如果不显示的设置Content-Type,那么默认是text/plain,这时服务器就不知道怎么解析数据了,所以才只能通过获取原始数据流的方式来进行解析请求数据。
当后台使用@RequestBody以对象的形式来接收数据时,在前台必须以application/json的形式进行传递,同时使用JSON.stringify(data)将json对象转换为json字符串。
当你使用application/x-www-form-urlencoded格式来传递数据时,tomcat会将其组装进一个Map中,后台只能用request.getParameter来访问。
原生Ajax默认格式:text/plain
Jquery Ajax默认格式(Map) + Form表单POST提交格式:application/x-www-form-urlencoded
字符流 Ajax格式(Map):application/json ( 同时使用JSON.stringify(data)将json对象转换为json字符串 )
文件上传:multipart/form-data
Application application_1512618719369_147804 failed 2 times due to ApplicationMaster for attempt app
今天遇到一个特别怪的问题,之前etl中的hive任务一直报错,持续一上午,也没有查出原因,错误的任务的日志也找到,原本可以找到原因,但是打开日志,心里面一凉,什么报错也没有,不知所错。最后观察报错的节点,最终集中到两台机器,那就看看是不是这两台机器的hadoop的程序引起的吗?看看他们的程序都在,但是查看nodemanager的日志一直报错,并且查看cpu,nodemanager进程占用的cpu达1000%多,马上眼前一亮,知道cpu占用太多,导致ap不能联系,导致任务失败,最后把这两台机器的nodemanager重启一下,观察了一下,任务不在报错。继续努力.............
application error 用php实现像JSP,ASP里Application那样的全局变量
复制代码 代码如下:
/**
* 功能:实现像JSP,ASP里Application那样的全局变量
* author: [url]www.itzg.net[/url]
* version: 1.0
* 版权:如许转载请保留版权声明
*/
/*+----------------example----------------------
require_once("Application.php");
$arr = array(0=>"Hi",1=>"Yes");
$a = new Application();
$a->setValue("t1","arui");
$a->setValue("arr",$arr);
$u = $a->getValue();
---------------------------------------------+*/
class Application
{
/**保存共享变量的文件*/
var $save_file = ''Application/Application'';
/**共享变量的名称*/
var $application = null;
/**序列化之后的数据*/
var $app_data = '''';
/**是否已经做过setValue的操作 防止频繁写文件操作*/
var $__writed = false;
/**
* 构造函数
*/
function Application()
{
$this->application = array();
}
/**
* 设置全局变量
* @param string $var_name 要加入到全局变量的变量名
* @param string $var_value 变量的值
*/
function setValue($var_name,$var_value)
{
if (!is_string($var_name) || empty($var_name))
return false;
if ($this->__writed)
{
$this->application[$var_name] = $var_value;
return;
}
$this->application = $this->getValue();
if (!is_array($this->application))
settype($this->application,"array");
$this->application[$var_name] = $var_value;
$this->__writed = true;
$this->app_data = @serialize($this->application);
$this->__writeToFile();
}
/**
* 取得保存在全局变量里的值
* @return array
*/
function getValue()
{
if (!is_file($this->save_file))
$this->__writeToFile();
return @unserialize(@file_get_contents($this->save_file));
}
/**
* 写序列化后的数据到文件
* @scope private
*/
function __writeToFile()
{
$fp = @fopen($this->save_file,"w");
@fwrite($fp,$this->app_data);
@fclose($fp);
}
}
?>
以上就介绍了application error 用php实现像JSP,ASP里Application那样的全局变量,包括了application error方面的内容,希望对PHP教程有兴趣的朋友有所帮助。
今天关于C# MVC 全局错误Application_Error中处理和包括Ajax请求的分享就到这里,希望大家有所收获,若想了解更多关于.net – Application_Error不会触发?、Ajax的text/plain、application/x-www-form-urlencoded和application/json、Application application_1512618719369_147804 failed 2 times due to ApplicationMaster for attempt app、application error 用php实现像JSP,ASP里Application那样的全局变量等相关知识,可以在本站进行查询。
本文标签: