微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从 SQLCLR 存储过程请求 HTTPS 时出错

如何解决从 SQLCLR 存储过程请求 HTTPS 时出错

我创建了一个 sql CLR 存储过程,它在数据库中发生 INSERT 时触发。存储过程然后使用 HttpWebRequest 进行 API JSON POST。

问题是 API 使用 SSL,所以当存储过程被触发时,我得到一个错误

消息 6522,级别 16,状态 1,过程 OnInsert,第 0 行 [批处理开始第 0 行]
在执行用户定义的例程或聚合“OnInsert”期间发生 .NET Framework 错误
System.Net.WebException:底层连接已关闭:无法为 SSL/TLS 安全通道建立信任关系。 System.Security.Authentication.AuthenticationException: 根据验证程序,远程证书无效。

我使用 sql Server 2014 和 .NET Framework 4.5,数据库设置为:

ALTER DATABASE TestDatabase SET TRUSTWORTHY ON;

Assembly 也是使用 .NET Framework 4.5,所使用的程序集的权限状态是:EXTERNAL_ACCESS;我尝试使用 UNSAFE 但仍然遇到相同的错误

这是我的存储过程:

public readonly static string _url = "https://localhost:44381/api/test";
[Microsoft.sqlServer.Server.sqlProcedure]
public static void OnInsert()
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_url);
    request.ContentType = "application/json; charset=utf-8";
    request.Method = "POST";
    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        string json = "{ \"Test\" : \"12345\" }";
        streamWriter.Write(json);
        streamWriter.Flush();
    }

    var httpResponse = (HttpWebResponse)request.GetResponse();

    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
    }
}

我尝试添加

    ServicePointManager.Expect100Continue = true;
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

但我仍然遇到同样的错误

当我添加

ServicePointManager.ServerCertificateValidationCallback += (sender,certificate,chain,sslPolicyErrors) => (true);

我收到此错误

消息 6522,级别 16,状态 1,过程 OnInsert,第 0 行 [批处理开始第 0 行]
在执行用户定义的例程或聚合“OnInsert”期间发生 .NET Framework 错误
System.Security.SecurityException:请求类型为“System.Security.Permissions.SecurityPermission、mscorlib、Version=4.0.0.0、Culture=neutral、PublicKeyToken=b77a5c561934e089”的权限失败。

我尝试通过 Postman 拨打相同的电话,但成功了。困扰我的是,我什至使用与 sql CLR 存储过程中相同的代码制作了一个控制台应用程序(.NET Framework 4.5),并且它也成功了。

这是我的控制台应用程序:

    public readonly static string _url = "https://localhost:44381/api/test";

    static void Main(string[] args)
    {
        Create();
    }
    
    public static void Create()
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_url);
        request.ContentType = "application/json; charset=utf-8";
        request.Method = "POST";

        using (var streamWriter = new StreamWriter(request.GetRequestStream()))
        {
            string json = "{ \"Test\" : \"12345\"}";
            streamWriter.Write(json);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)request.GetResponse();

        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
        }
    }

提前致谢!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。