InnerException 为: {"Server cannot set content type after HTTP headers have been sent."}
经debug发现,是在:
1 public string ContentType
2 {
3 get
4 {
5 return this._contentType;
6 }
7 set
8 {
9 if (this._headersWritten)
10 {
11 if (this._contentType != value)
12 {
13 throw new HttpException(System.Web.SR.GetString("Cannot_set_content_type_after_headers_sent"));
14 }
15 }
16 else
17 {
18 this._contentTypeSet = true;
19 this._contentType = value;
20 }
21 }
22 }
3 get
4 {
5 return this._contentType;
6 }
7 set
8 {
9 if (this._headersWritten)
10 {
11 if (this._contentType != value)
12 {
13 throw new HttpException(System.Web.SR.GetString("Cannot_set_content_type_after_headers_sent"));
14 }
15 }
16 else
17 {
18 this._contentTypeSet = true;
19 this._contentType = value;
20 }
21 }
22 }
抛出的异常,调用是在:
private void SetIntrinsics(HttpContext context, bool allowAsync)
{
......
HttpCapabilitiesBase browser = this._request.Browser;
this._response.ContentType = browser.PreferredRenderingMime;
......
HttpCapabilitiesBase browser = this._request.Browser;
this._response.ContentType = browser.PreferredRenderingMime;
当第二次设置 ContentType并且两次不一致时,就会出现这个错误. 那么第一次是我们自己的程序设置的,类型是Text/XML.第二次是系统设置的,
值是text/html .这样Exception就出现了.
我们需要返回的类型是XML,因此需要修改第二次设置的值,也就是说要更改 browser.PreferredRenderingMime,即this._request.Browser.所以:
在 Server.Transfer前加入如下代码:
1 MyHttpBrowserCapabilities browse = new MyHttpBrowserCapabilities();
2 browse.Capabilities = new Hashtable();
3 BrowserCapabilitiesFactory factroy = new BrowserCapabilitiesFactory();
4 factroy.ConfigureBrowserCapabilities(HttpContext.Current.Request.Headers, browse);
5 HttpContext.Current.Request.Browser = browse;
6 HttpContext.Current.Server.Transfer(....
3 BrowserCapabilitiesFactory factroy = new BrowserCapabilitiesFactory();
4 factroy.ConfigureBrowserCapabilities(HttpContext.Current.Request.Headers, browse);
5 HttpContext.Current.Request.Browser = browse;
6 HttpContext.Current.Server.Transfer(....
Class MyHttpBrowserCapabilities 也很简单:
1 public class MyHttpBrowserCapabilities : HttpBrowserCapabilities
2 {
3
4 public override string PreferredRenderingMime
5 {
6 get
7 {
8 return "Text/XML";
9 }
10 }
11 }
3
4 public override string PreferredRenderingMime
5 {
6 get
7 {
8 return "Text/XML";
9 }
10 }
11 }
指示Mime一样而已.这样就不会出现Exception了.