2016-01-29 430 views
-1

在我的C#項目中,我有2個Web端點:「Start.ashx」和「Query.ashx」。 當我開始我的項目,我可以打類似「http://localhost/site/start.ashx?text=abc」和「http://localhost/site/Query.asxh?text=abc從一個ashx發出Http請求到另一個ashx

我的問題是在我的start.ashx,我怎樣才能創建一個web請求query.ashx兩個端點?

我能想到的一件事就是這樣做:但我認爲最好不要在我的請求中放置本地主機。

WebRequest request = WebRequest.Create ("http://localhost/site/Query.ashx?text=abc"); 

有沒有更好的方法?

謝謝。

+6

爲什麼你需要提出網絡請求?如果它在同一個項目中,則調用相同的應用程序代碼。 –

回答

0

通過HttpContext您可以從Request對象獲得Url,並使用它來構建您的WebRequest URL。

public void ProcessRequest(HttpContext context) 
{ 
    string url = context.Request.Url.AbsoluteUri; 
    // ---- url ==> "http://localhost:21310/site/htmlpage.ashx" 
    string baseUrl = context.Request.Url.Authority; 
    // ---- baseUrl ==> "localhost:21310" 
    WebRequest request = WebRequest.Create ("http://"+ baseUrl +"/site/Query.ashx?query=abc"); 
    // rest of the logic 
} 

然而,如果兩個端點都在同一個項目,它是沒有效率做一個HTTP請求來獲取數據

0

典型的方式做,這是創建一個包含另一大類「肉'的查詢代碼,然後在兩個地方調用它;

// in QueryService.cs, you define a library for querying... 
public class QueryService 
{ 
    public DataTable PerformQuery(string searchTerm) 
    { 
     // your query logic goes here. Return a logical result like a DataTable, some JSON, etc. 
    } 
} 

// in Query.ashx, call your query service; 
public void ProcessRequest(HttpContext context) 
{ 
    var searchTerm = context.Request.QueryString["query"]; 
    var results = new QueryService().PerformQuery(searchTerm); 
    context.Response.Write(...results...); 
} 

// in Start.ashx, call your query service again; 
public void ProcessRequest(HttpContext context) 
{ 
    var searchTerm = context.QueryString["homepage"]; 
    var results = new QueryService().PerformQuery(searchTerm); 
    context.Response.Write(...results...); 
}  

這樣,你的應用程序可以執行查詢,用少量代碼,而無需進行其他Web請求這是昂貴的,通過使標準的函數調用的任何部分。