2009-09-05 29 views
8

Với URL A được chuyển hướng đến trang web bên thứ 3 B, trong ứng dụng của tôi, tôi cần tìm URL B cho url A đã cho và chèn URL vào DB, đây có thể là cửa sổ ứng dụng hoặc web hoặc bất kỳ cách nào là nhanh hơn và dễ dàng hơn bằng cách sử dụng C#! Cảm ơn!Một cách để tìm ra URL chuyển hướng

P.S. Tôi không yêu cầu mã để chèn vào DB.

+2

Phụ thuộc cách chuyển hướng hoạt động. Phía máy chủ? Phía máy khách (tức là JS)? Hãy thử tìm nạp URL với bất kỳ trình bao bọc http nào C# có và theo dõi bất kỳ 301s/302 nào. Nếu bạn may mắn, thậm chí có thể có một thư viện để làm điều đó cho bạn. Điều gì xảy ra nếu B chuyển hướng đến C? Bạn có muốn lưu trữ B hoặc C không? Bạn sẽ theo dõi chuyển hướng bao xa? Điều gì sẽ xảy ra nếu C chuyển hướng đến B? Đảm bảo bạn tránh các vòng chuyển hướng vô hạn bằng cách theo dõi những địa chỉ bạn đã truy cập hoặc đặt giới hạn chuyển hướng (mà tôi nghĩ là cách Firefox/Chrome xử lý vấn đề này). –

+0

Ví dụ bên máy chủ sẽ ổn ... đây chỉ là công cụ trích xuất dữ liệu (tức là URL cuối cùng) nên không cần phải lạ mắt ... có thể được thực hiện theo bất kỳ cách nào! "A" sẽ luôn chuyển hướng đến "B" và không còn chuyển hướng nào để xảy ra thêm từ đó là một thực tế được thiết lập. –

+0

Mã phía khách hàng không bị tổn thương quá ... Im giả định một ứng dụng biểu mẫu giành chiến thắng với một thể hiện của IE bên trong nên làm công việc ... chỉ cần không chắc chắn –

Trả lời

10

WebRequest sau đổi hướng mà không cần người dùng can thiệp, vì vậy nếu chuyển hướng đang sử dụng 301/302 mã trạng thái thì đây sẽ làm việc

WebRequest request = WebRequest.Create(destination); 
WebResponse response = request.GetResponse(); 
Console.WriteLine(response.ResponseUri); 

Nếu chuyển hướng được tạo ra sử dụng javascript hoặc HTTP-Tương đương thẻ meta sau đó bạn' đang làm để phân tích trang và tìm kiếm những trang đó. Gói nhanh nhẹn HTML có lẽ là cách tốt nhất để làm điều này.

Để thực hiện việc này một chút nữa sau đây là một lớp học mà sẽ tự giải quyết các mã trạng thái HTTP chuyển hướng chính, xây dựng một lịch sử như nó đi

/// <summary> 
/// Digs through HTTP redirects until a non-redirected URL is found. 
/// </summary> 
public class Digger 
{ 
    /// <summary> 
    /// Initializes a new instance of the <see cref="Digger"/> class. 
    /// </summary> 
    public Digger() : this(20) 
    {    
    } 

    /// <summary> 
    /// Initializes a new instance of the <see cref="Digger"/> class. 
    /// </summary> 
    /// <param name="maximumDepth">The maximum depth of redirects to parse.</param> 
    public Digger(int maximumDepth) 
    { 
     this.MaximumDepth = maximumDepth; 
    } 

    /// <summary> 
    /// Gets the maximum depth of redirects to parse. 
    /// </summary> 
    /// <value>The maximum depth of redirects to parse.</value> 
    public int MaximumDepth 
    { 
     get; 
     private set; 
    } 

    /// <summary> 
    /// Resolves any redirects at the specified URI. 
    /// </summary> 
    /// <param name="destination">The initial URI.</param> 
    /// <returns>The URI after resolving any HTTP redirects.</returns> 
    public Uri Resolve(Uri destination) 
    { 
     List<Uri> redirectHistory = new List<Uri>(); 
     return this.Resolve(destination, redirectHistory); 
    } 

    /// <summary> 
    /// Resolves any redirects at the specified URI. 
    /// </summary> 
    /// <param name="destination">The initial URI.</param> 
    /// <param name="redirectHistory">A collection of <see cref="Uri"/> objects representing the redirect history.</param> 
    /// <returns>The URI after resolving any HTTP redirects.</returns> 
    public Uri Resolve(Uri destination, ICollection<Uri> redirectHistory) 
    { 
     redirectHistory.Add(destination); 
     return this.Resolve(destination, this.MaximumDepth, redirectHistory); 
    } 

    /// <summary> 
    /// Resolves any redirects at the specified URI. 
    /// </summary> 
    /// <param name="destination">The initial URI.</param> 
    /// <param name="hopsLeft">The maximum number of redirects left to follow.</param> 
    /// <param name="redirectHistory">A collection of <see cref="Uri"/> objects representing the redirect history.</param> 
    /// <returns>The URI after resolving any HTTP redirects.</returns> 
    private Uri Resolve(Uri destination, int hopsLeft, ICollection<Uri> redirectHistory) 
    { 
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destination); 
     request.AllowAutoRedirect = false; 
     request.Method = "HEAD"; 

     HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 

     Uri resolvedUri; 

     if (response.StatusCode == HttpStatusCode.Redirect || 
      response.StatusCode == HttpStatusCode.Moved || 
      response.StatusCode == HttpStatusCode.MovedPermanently) 
     { 
      if (hopsLeft > 0) 
      { 
       Uri redirectUri = new Uri(response.GetResponseHeader("Location")); 
       if (redirectHistory.Contains(redirectUri)) 
       { 
        throw new Exception("Recursive redirection found"); 
       } 

       redirectHistory.Add(redirectUri); 
       resolvedUri = this.Resolve(redirectUri, hopsLeft - 1, redirectHistory); 
      } 
      else 
      { 
       throw new Exception("Maximum redirect depth reached"); 
      } 
     } 
     else 
     { 
      resolvedUri = response.ResponseUri; 
     } 

     return resolvedUri;    
    } 
} 
+0

Cảm ơn các công trình hoàn hảo! –

+0

Điều này sẽ không hoạt động nếu tiêu đề Vị trí chứa URI tương đối. Tôi tin: 'Uri redirectUri; if (! Uri.TryCreate (vị trí, UriKind.Absolute, ra redirectUri)) {if (! Uri.TryCreate (response.ResponseUri, location, out redirectUri)) {ném WebException mới ("Chuyển hướng không hợp lệ"); }} 'sẽ làm việc trong nhiều/hầu hết/(tất cả nếu các ngôi sao sắp xếp) các trường hợp, nhưng chưa thử nghiệm kỹ lưỡng nó. –

+0

Thật là một câu trả lời tuyệt vời. – Ikaso

0
Uri MyUrl = Request.UrlReferrer; 
Response.Write("Referrer URL Port: " + Server.HtmlEncode(MyUrl.Port.ToString()) + "<br>"); 
Response.Write("Referrer URL Protocol: " + Server.HtmlEncode(MyUrl.Scheme) + "<br>"); 

Như những gì tôi hiểu được từ câu hỏi của bạn, bạn có thể sử dụng mã như thế này để bạn có thể xem url trước đó và lưu nó vào db bằng cách sử dụng LINQ hoặc các phương pháp ADO.NET khác.

Tôi giả sử rằng bạn biết cách lưu bản ghi trong db bằng LINQ. Nếu bạn không làm theo liên kết này: LINQ to SQL - 5 Minute Overview

Hy vọng điều đó sẽ hữu ích.

Các vấn đề liên quan