How to get around DnsRecordListFree error in .NET Framework 4.0?
I am doing an MxRecordLookup. I am getting an error when calling the DnsRecordListFree in the .NET Framework 4.0. I am using Windows 7. How do I get around it? Here is the error:
System.MethodAccessException: Attempt b开发者_运维知识库y security transparent method to call native code through method.
Here is my code:
[DllImport("dnsapi", EntryPoint = "DnsQuery_W", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
private static extern int DnsQuery([MarshalAs(UnmanagedType.VBByRefStr)]ref string pszName, QueryTypes wType, QueryOptions options, int aipServers, ref IntPtr ppQueryResults, int pReserved);
[DllImport("dnsapi", CharSet = CharSet.Auto, SetLastError = true)]
private static extern void DnsRecordListFree(IntPtr pRecordList, int FreeType);
public List<string> GetMXRecords(string domain)
{
List<string> records = new List<string>();
IntPtr ptr1 = IntPtr.Zero;
IntPtr ptr2 = IntPtr.Zero;
MXRecord recMx;
try
{
int result = DnsQuery(ref domain, QueryTypes.DNS_TYPE_MX, QueryOptions.DNS_QUERY_BYPASS_CACHE, 0, ref ptr1, 0);
if (result != 0)
{
if (result == 9003)
{
//No Record Exists
}
else
{
//Some other error
}
}
for (ptr2 = ptr1; !ptr2.Equals(IntPtr.Zero); ptr2 = recMx.pNext)
{
recMx = (MXRecord)Marshal.PtrToStructure(ptr2, typeof(MXRecord));
if (recMx.wType == 15)
{
records.Add(Marshal.PtrToStringAuto(recMx.pNameExchange));
}
}
}
finally
{
DnsRecordListFree(ptr1, 0);
}
return records;
}
Read Security Changes in the .NET Framework 4 to understand what transparent and critical code is. By default, in .NET 4, any code in an assembly marked with AllowPartiallyTrustedCallersAttribute
is transparent, which means it cannot call critical code (code marked with SecurityCriticalAttribute
). Only security safe critical (marked with SecuritySafeCriticalAttribute
) or critical code can call critical code. And security safe critical can be called by transparent called.
In short:
Transparent can call Transparent or Security Safe Critical
Security Safe Critical can call Security Safe Critical or Critical
Critical can call Critical
Enable Code Analysis with the Microsoft Security rules set to see warnings about bad security calls. Note that you can revert back to how security worked in .NET Framework 2.0 (all code is critical) by applying [assembly: SecurityRules(SecurityRuleSet.Level1)]
or removing AllowPartiallyTrustedCallersAttribute
. See Security-Transparent Code, Level 2 for more information.
To comply with the new rules, GetMXRecords
should become SecuritySafeCritical
and the DLL import calls must be marked with SecurityCritical
.
精彩评论