在SQL 2008 CLR UDF中使用HttpWebrequest解决不稳定行为

时间:2009-03-21 02:22:58

标签: c# .net sql-server clr user-defined-functions

我们目前正在尝试实现一个sql server 2008 udf来扩展缩短的URL。我们对大多数主要的网址缩短服务都很有效。然而,在看似随机的时间它会“挂起”并拒绝对某个域(例如bit.ly)起作用,而后续对其他服务的调用(例如tinyurl.com)将继续成功。

我们最初认为这是由于url缩短提供程序的某种阻塞,但停止并重新启动dbserver服务会导致后续请求成功。可能是SQL服务器以某种方式汇集传出的http连接?

这是代码......

using System;
using System.Data;
using System.Net;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

public partial class UserDefinedFunctions
{
    [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlString UrlExpander(string url)
    {
            // Set up the Webrequest
            HttpWebRequest wr = (HttpWebRequest)HttpWebRequest.Create(url);
            try
            {

            // Set autoredirect off so the redirected URL will not be loaded
            wr.AllowAutoRedirect = false;

            // Get the response
            HttpWebResponse wresp = (HttpWebResponse)wr.GetResponse();

            return new SqlString(wresp.Headers["Location"].ToString());
        }
        catch (Exception ex)
        {
            wr.Abort();
            throw ex;

        }


    }
};

2 个答案:

答案 0 :(得分:1)

你错过了wresp.Close()。

答案 1 :(得分:0)

鉴于Jesse的反馈以及我们希望有一个返回正确扩展的url或NULL的函数,我们提出了以下内容,它似乎处理了1000个缩小的URL而没有进一步的问题:

[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString UrlExpander(string url)
{
    // Set up the Webrequest
    try
    {
        HttpWebRequest wr = (HttpWebRequest)HttpWebRequest.Create(url);
        try
        {
            // Set autoredirect off so the redirected URL will not be loaded
            wr.AllowAutoRedirect = false;

            // Get the response
            HttpWebResponse wresp = (HttpWebResponse)wr.GetResponse();
            wresp.Close();

            if (wresp != null)
                return new SqlString(wresp.Headers["Location"].ToString());
        }
        finally
        {
            if (wr != null)
                wr.Abort();
        }
    }
    catch
    {
    }

    return null;

}