C#WebApi 2 CORS在ExecuteReader时不工作
我在C#中完成了基于令牌身份验证的webapi,我的问题是当我需要将用户验证到另一台服务器的SQL Server数据库时,一切正常,直到我针对连接执行读卡器,然后它在浏览器中返回CORS错误,当我移除读卡器并返回令牌时,但我需要使用SQL Server进行验证,以下是我的代码:C#WebApi 2 CORS在ExecuteReader时不工作,c#,angularjs,cors,asp.net-web-api2,C#,Angularjs,Cors,Asp.net Web Api2,我在C#中完成了基于令牌身份验证的webapi,我的问题是当我需要将用户验证到另一台服务器的SQL Server数据库时,一切正常,直到我针对连接执行读卡器,然后它在浏览器中返回CORS错误,当我移除读卡器并返回令牌时,但我需要使用SQL Server进行验证,以下是我的代码: public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
string nombre = "";
string cadenaConexion = "Data Source=ipSQLServer;Initial Catalog=EDELIVERY;Persist Security Info=True;User ID=userDataBase;Password=PasswdUserDataBase";
SqlConnection conn = new SqlConnection(cadenaConexion);
conn.Open();
string sql = "select * from Usuario a inner join TipoUsuario b on a.CodTipoUsuario = b.Codigo where a.Usuario = '" + context.UserName + "' and a.Clave = '" + context.Password + "');";
SqlCommand cmd = new SqlCommand(sql);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
nombre = reader.GetString(0).ToString().Trim();
}
}
reader.Close();
conn.Close();
if (context.UserName == "admin" && context.Password == "admin")
{
identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
identity.AddClaim(new Claim("username", "admin"));
identity.AddClaim(new Claim(ClaimTypes.Name, "Nombre Admin"));
context.Validated(identity);
}
else if (context.UserName == "user" && context.Password == "user")
{
identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
identity.AddClaim(new Claim("username", "user"));
identity.AddClaim(new Claim(ClaimTypes.Name, "Nombre Usuario"));
context.Validated(identity);
}
else {
context.SetError("error_grant", "Provided username and password is incorrect");
return;
}
}
以下是客户端的代码,使用angularjs:
loginApi: function (infoLogin) {
var deferred = $q.defer();
var url = "http://localhost:51372/token";
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: 'username='+infoLogin.usuario+'&password='+infoLogin.passwd+'&grant_type=password'
}).then(function (resp, status, headers, config) {
deferred.resolve(resp);
},
function (err, status, headers, config) {
deferred.reject(err);
});
return deferred.promise;
}
我建立了一个简单的数据库连接,只是为了检索一些数据,举个例子,如果有人能帮助我,谢谢。您必须在web api中启用CORS 请尝试将其放入web.config:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept,Authorization" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
</system.webServer>