C#WebApi 2 CORS无法正常执行ExecuteReader

时间:2017-02-16 16:53:55

标签: c# angularjs cors asp.net-web-api2

我在C#中完成了基于webapi的令牌认证,我的问题是当我需要将用户验证到另一个服务器中的SQL Server数据库时,一切正常,直到我对连接执行读取器,然后它返回错误浏览器中的CORS,当我删除阅读器工作正常并返回令牌,但我需要用SQL Server验证,这是我的代码:

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;
        }

我做了一个简单的数据库连接,只是为了检索一些数据,只是为了这个例子,谢谢,如果有人可以帮助我。

1 个答案:

答案 0 :(得分:2)

您必须在网络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>