2016-12-27 27 views
1

我從ActionResult繼承了一個類,然後重寫了ExecuteResult方法。重寫ExecuteResult方法並設置Content-Type

public class CustomResult : ActionResult 
{ 
    public object Result { get; set; } 
    public int StatusCode { get; private set; } 

    public CustomResult(int statusCode, object Result) 
    { 
     this.Result = Result; 
     this.StatusCode = statusCode; 
    } 

    public override void ExecuteResult(ControllerContext context) 
    { 
     if (context == null) 
      throw new ArgumentNullException("context"); 

     context.HttpContext.Response.StatusCode = StatusCode; 
     if (StatusDescription != null) 
      context.HttpContext.Response.StatusDescription = StatusDescription; 

     HttpResponseBase Response = context.HttpContext.Response; 
     Response.Charset = "UTF-8"; 
     Response.ContentType = "application/json"; 
     context.HttpContext.Response.Write(JsonConvert.SerializeObject(this)); 
    } 
} 

當我從控制器返回CustomResult對象,返回的Content-Type的觀點始終是「text/html的」,而不是「應用/ JSON的」關於CustomResult類中設置好的。

如果我在本地運行此應用程序一切正常,但是當我將此應用程序部署到Azure應用程序服務時,Content-Type始終爲text/html。

回答

0

我找到了解決方案!我已將此行Response.TrySkipIisCustomErrors = true;添加到Response對象。

+0

嗯,這聽起來像一個黑客。我猜想你的web管道中出現了錯誤,導致響應成爲「text/html」的IIS網頁錯誤頁面。 – Saca

+0

我已經做了一些測試,並且這個問題只發生在HTTP 500狀態碼的情況下。我還沒有找到關於Azure WebApp IIS管道的任何文檔,因此我認爲對於HTTP 500狀態代碼,Azure具有修改對text/html Content-Type的響應的默認行爲。在Azure門戶中,我沒有找到任何屬性來修改此行爲。這也是在本地調試中正確工作的原因。 – Matteo

0

根據我的經驗,它可以在Azure Web App中正常工作。即使我將WebApp發佈到Azure環境,它也能正常工作。如果可能,請嘗試使用Fiddler工具進行檢查。

enter image description here

+0

我已經使用本地實例和Azure Web應用程序中的Fiddler流量進行捕獲,因此,我開始響應application/json本地和Azure中的text/html。我要瘋了... – Matteo

+0

請嘗試部署新的WebApp。並檢查是否在webconfig中設置了某些內容,或者我已部署到新的WebApp但Applettings –

+0

存在相同的問題。在Azure上的應用程序屬性或web.config中,沒有可能表明內容類型的行爲不同的設置。 – Matteo