2013-10-23 41 views
0

ASP.NET消息處理程序返回JSON是否有可能存在以下情況:如果自定義頁眉發現

創建一個消息處理程序,將檢查每一個傳入的請求。如果請求包含一個自定義標題鍵:「My-Header」,它的值是:「True」,那麼停止請求並返回一個自定義json到客戶端,否則,如果標題不存在或標題存在但值是「假」,然後允許請求通過。

回答

0

聽起來像你會沿着下面顯示的代碼行。假設您想要發回的JSON在這裏表示爲ErrorModel。要將處理程序添加到ASP.NET Web API處理程序管道中,請參閱this good article瞭解它如何連接。

public class MyHeaderHandler : DelegatingHandler 
{ 
    protected override Task<HttpResponseMessage> SendAsync(
     HttpRequestMessage request, 
     CancellationToken cancellationToken) 
    { 
     string headerTokenValue; 
     const string customHeaderKey = "My-Header"; 

     if (!request.Headers.TryGetValues(
       customHeaderKey, 
       out headerTokenValue) 
      || headerTokenValue.ToLower() != "true") 
     { 
      return base.SendAsync(request, cancellationToken); 
     } 

     return Task<HttpResponseMessage>.Factory.StartNew(
      () => 
       { 
        var response = new HttpResponseMessage(
         HttpStatusCode.Unauthorized); 
        var json = JsonConvert.SerializeObject(
         new ErrorModel 
         { 
          Description = "error stuff", 
          Status = "Ooops" 
         }); 
        response.Content = new StringContent(json); 
        // Ensure return type is JSON: 
        response.Content.Headers.ContentType = 
         new MediaTypeHeaderValue("application/json"); 

        return response;  
       }); 
    } 
} 
+0

謝謝!我想我現在明白了。然而Stephen Cleary在我的一篇文章中提到,在服務器端代碼中使用Task並不是一個好習慣。 – user2818430

0

我會猜測也許這樣更好?

............ 

HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Forbidden); 

var json = JsonConvert.SerializeObject(
        new ErrorModel 
        { 
         Description = "error stuff", 
         Status = "Ooops" 
        }); 
response.Content = new StringContent(json); 

var tcs = new TaskCompletionSource<HttpResponseMessage>(); 
tcs.SetResult(response); 
return tcs.Task;