且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

调用CLR函数时出现SecurityException错误

更新时间:2022-10-15 16:33:31

您必须创建具有外部访问权限集的程序集.还必须对程序集进行签名或将数据库设置为可信任的,并且数据库所有者必须授予外部访问程序集权限.不需要上面的许可和断言代码.

You must create the assembly with external access permission set. The assembly must also be signed or the database set as trustworthy and the database owner granted the external access assembly permission. The permission and assert code above is not required.

例如

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

public partial class UserDefinedFunctions
{
    [Microsoft.SqlServer.Server.SqlFunction(DataAccess=DataAccessKind.None)]
    public static SqlString getname(String ipAddress)
    {
        IPHostEntry host = Dns.GetHostEntry(ipAddress);
        return new SqlString(host.HostName);
    }
}

将代码保存到C:\ resolve \ resolve.cs并进行编译...

Save the code to C:\resolve\resolve.cs and compile it...

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /t:library /out:C:\resolve\resolve.dll C:\resolve\resolve.cs

如果不是本地实例,请将.dll复制到服务器.然后创建对象...

Copy the .dll to the server if not a local instance. Then create the objects...

USE [master]
GO
CREATE DATABASE [clr]; 
GO
ALTER AUTHORIZATION ON DATABASE::[clr] TO [sa]; 
GO
ALTER DATABASE [clr] SET TRUSTWORTHY ON; 
GO
USE [clr]; 
GO
CREATE ASSEMBLY [assResolve] FROM 'C:\resolve\resolve.dll' 
WITH PERMISSION_SET=EXTERNAL_ACCESS; 
GO
CREATE FUNCTION [fnGetHostName](@ipAddress nvarchar(255)) RETURNS nvarchar(255) 
AS EXTERNAL NAME [assResolve].[UserDefinedFunctions].[getname]; 
GO
SELECT [dbo].[fnGetHostName](N'8.8.8.8') as [host]; 
GO
USE [master]