[英]Windows impersonate [SQL, ASP.NET, C#]
我尝试在asmx Web服务中使用Windows模拟来读取sql数据库。
现在我调用方法GetDataSet,但是它在客户端出现此错误:
System.Web.Services.Protocols.SoapException:服务器无法处理请求。 ---> System.Exception:数据库'master'中的CREATE DATABASE权限被拒绝。 尝试为文件D:\\ work \\ WebService \\ App_Data \\ ORLDatabase.mdf附加自动命名的数据库失败。 存在具有相同名称的数据库,或者无法打开指定的文件,或者该数据库位于UNC共享上。
我使用WindowsIdentity.GetCurrent()检查Windows在代码中模拟,当前的身份良好。该帐户对数据库文件具有完全控制权,但存在错误。 有人可以帮我吗,我不使用sql。 我先尝试使用google,但是找不到能解决我的问题的解决方案。 谢谢
public class Service : System.Web.Services.WebService
{
public TicketHeader Ticket;
public DataSet ds;
private string machine = "pcName";
public string userName = "********";
public string password = "*********";
public IntPtr token;
public WindowsImpersonationContext impersonationContext;
[DllImport(@"D:\Windows\System32\advapi32.dll")]
public static extern bool LogonUser
(string lpszUserName, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out int phToken);
public void Login()
{
int returnedToken;
if (LogonUser(userName, machine, password, 3, 0, out returnedToken))
{
token = new IntPtr(returnedToken);
}
}
[WebMethod]
public DataSet GetDataSet(string id)
{
DataSet ds = null;
Login();
impersonationContext = WindowsIdentity.Impersonate(token);
SqlConnection conn = null;
SqlDataAdapter da = null;
try
{
string sql = "Select * from Table";
conn = new SqlConnection(@"Data Source=.\SQLEXPRESS; Integrated Security=True;" +
@"AttachDbFilename=|DataDirectory|\ORLDatabase.mdf;");
conn.Open();
da = new SqlDataAdapter(sql, conn);
ds = new DataSet();
da.Fill(ds, "Table");
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
if (conn != null)
conn.Dispose();
}
impersonationContext.Undo();
return ds;
}
}
您创建的Windows帐户也必须是数据库引擎上的登录名。 在SQL Server Management Studio中:服务器名->安全性->登录| 右键单击->新登录。 我怀疑文件权限是否足够。
我在上述解决方案上遇到了问题,但是进行了一些更改。
更改之后,可以在我的站点上成功运行的本地用户可以使用我的域凭据连接到数据库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.