2013-04-30 66 views
2

我有一個Asp.net Web API項目,它有幾個CRUD方法。Asp.net Web Api重定向請求

在這些方法之上,我想添加一個授權服務,該服務讀取Authorization標頭並阻止用戶訪問資源(如果它們未被授權)。

// Method on internal IP Project 
public class InternalController : ApiController 
{ 
    public void Create(CreateRequest request) 
    { 
     // implement the method 
    } 
} 

// Method on public IP Project 
public class ExternalController : ApiController 
{ 
    public async Task Create(CreateRequest request) 
    { 
     // validate Authorization header and throw exception if not valid 

     using (HttpClient client = new HttpClient()) 
     { 
      string parameters = string.Format("param1={0}&param2={1}", request.Param1, request.Param2); 

      client.BaseAddress = new Uri("http://192.168.1.1/"); 
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

      HttpResponseMessage response = await client.GetAsync("api/internal/create?" + parameters); 
      response.EnsureSuccessStatusCode(); 
     } 
    } 
} 

是否有任何方法可以更輕鬆地將外部API的請求「重定向」到內部API?

現在,我必須手動重新創建在ExternalAPI中收到的所有參數,並將它們發送到InternalAPI中,即使它們相同。

我可以讓HttpClient自動發送我在ExternalAPI方法中使用的HttpRequestMessage (Request)對象嗎?

+0

是'InternalController'和'ExternalController'在同一個web項目? – haim770 2013-04-30 09:18:32

+0

不,他們是不同的項目 – Catalin 2013-04-30 09:21:56

回答

4

當談到ASP.NET Web API。 HttpClient不會自動重定向你。當你已經成爲內部服務的迴應時,你可以將它傳遞給外部。或者您可以重定向您的操作,如here

要從REST角度爲客戶端正確重定向,請使用HTTP重定向頭和repsonse代碼。例如HTTP response code 302。然後客戶端應該能夠對這樣的響應代碼做出反應並從Location頭獲得重定向地址。但它是關於客戶端的重定向。

當談到來自架構的來自API的一些內部服務的調用時。您有以下選擇:

  1. 打電話給你的內部服務作爲類方法
  2. 製作服務,以服務呼叫
  3. 安裝消息隊列或公交車,你的API將通過服務總線與它通信。

打電話給你的內部服務作爲類方法 很容易。服務電話沒有影響和延遲。但是你應該參考彙編,並不總是可能的。或者,這樣的方式可能是不可能的,因爲要求

製作服務,以服務呼叫 有缺點:你的服務是緊密耦合的,你有延遲,應等待來自內部的服務響應。這被認爲是不好的做法。但作爲服務巴士的第一步,這可能是一個很好的臨時解決方案。

安裝消息隊列或總線,您的API將通過服務總線與它通信。 您的服務是分離和獨立的。你不應該等待迴應。但它在技術上難以建立,使你的架構和基礎設施更復雜/

作爲總結 有從您的架構箱沒有最好的方式,你應該根據自己的需要選擇替代品。

+0

非常全面的答案!我想我會去使用服務類,也因爲我可以參考我需要的程序集。 – Catalin 2013-04-30 09:29:16

0

下面是示例代碼發佈的數據網絡API: -

var handler = new HttpClientHandler {UseDefaultCredentials = true}; 
     using (var client = new HttpClient(handler)) 
     { 
      client.BaseAddress = new Uri("https://IE url.com"); 
      client.DefaultRequestHeaders.Accept.Clear(); 
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

    var postDataObject = new 
       { 
        SCName = properties.Site.PortalName, 
        TotalSites = properties.Web.Webs.Count 
    }; 

    var jsonPostData = new JavaScriptSerializer().Serialize(postDataObject); 
       HttpContent content = new StringContent(jsonPostData, System.Text.Encoding.UTF8, "application/json"); 
       HttpResponseMessage response = client.PostAsync("/controllerclassname/InsertUpdateDataOperation", content).Result; 
       if (response.IsSuccessStatusCode) 
       { 
     //Check the response here 
        // var webApiResponse = response.Content.ReadAsStringAsync().Result;      
       }