weixin_33701294 2017-03-02 08:21 采纳率: 0%
浏览 134

DisableCors无法正常工作

I have the following WebApi C# Controller:

[RoutePrefix("api/users")]
[EnableCors(origins: "http://pincopalli.com", headers: "*", methods: "*")]
public class UserController : ApiController
{
  [Route("checkusername/{_username}")]
  [HttpGet]
  public bool CheckUsername(string _username)
  {
    try
    {
      using (BugMeEntities database = new BugMeEntities())
      {
          database.Database.Connection.Open();

          if (database.users.Where(x => x.name.Equals(_username)).FirstOrDefault() != null)
          {
              return false;
          }
      }

      return true;
    }
    catch(Exception ex)
    {
      return false;
    }
  }

  [Route("checkemail/{_email}")]
  [HttpGet]
  public bool CheckEmail(string _email)
  {
    try
    {
      using (BugMeEntities database = new BugMeEntities())
      {
          database.Database.Connection.Open();

          if (database.users.Where(x => x.email.Equals(_email)).FirstOrDefault() != null)
          {
              return false;
          }
      }

      return true;
    }
    catch (Exception ex)
    {
      return false;
    }
  }

  [DisableCors]
  [Route("register")]
  [HttpPost]
  public User.Response Register([FromBody]User.Register _user)
  {
    try
    {
      if(_user.GetType().GetProperties().Select(x => x.GetValue(_user)).Any(x => x != null))
      {
          using (BugMeEntities database = new BugMeEntities())
          {
              database.Database.Connection.Open();

              if(database.users.Where(x => x.name.Equals(_user.username)).Count() == 0)
              {
                  if (database.users.Where(x => x.email.Equals(_user.email)).Count() == 0)
                  {
                      string newPassword = randomPassword();

                      bool emailSent = Utility.newMail(_user.email, "Benvenuto su BugMe", $"Benvenuto <b>{_user.username}</b>,<br>La nuova password necessaria per accedere è: <b>{newPassword}</b>.");

                      if (emailSent)
                      {
                          users user = new users { name = _user.username, password = newPassword, email = _user.email, active = true };
                          database.users.Add(user);
                          database.SaveChanges();
                      }

                      return new User.Response { status = true, message = $"Congratulazioni, ti sei registrato con successo! 
Abbiamo inviato un'email a {_user.email} contenente la password necessaria per accedere." };
                  }
                  else
                  {
                      throw new ArgumentException("Email non disponibile.");
                  }
              }
              else
              {
                  throw new ArgumentException("Username non disponibile.");
              }
          }
      }
      else
      {
          throw new ArgumentException("Compilare tutti i campi del form.");
      }
    }
    catch(Exception ex)
    {
      return new User.Response { status = false, message = ex.Message };
    }
  }

  [DisableCors]
  [Route("login")]
  [HttpPost]
  public User.Response Login([FromBody]User.Login _user)
  {
    try
    {
      if (_user.GetType().GetProperties().Select(x => x.GetValue(_user)).Any(x => x != null))
      {
          using (BugMeEntities database = new BugMeEntities())
          {
              database.Database.Connection.Open();

              users userFetch = database.users.Where(x => x.name.Equals(_user.username) && x.password.Equals(_user.password) && x.active.Equals(true)).FirstOrDefault();

              if (userFetch != null)
              {
                  User.Session user = new User.Session
                  {
                      id = userFetch.id,
                      username = userFetch.name,
                      password = userFetch.password,
                      email = userFetch.email
                  };

                  return new User.Response { status = true, message = JsonConvert.SerializeObject(user) };
              }
              else
              {
                  throw new ArgumentException("Utente non trovato.");
              }
          }
      }
      else
      {
          throw new ArgumentException("Compilare tutti i campi del form.");
      }
    }
    catch(Exception ex)
    {
      return new User.Response { status = false, message = ex.Message };
    }
  }

  private static string randomPassword(int lunghezza = 8)
  {
    const string caratteri = "ABCDEFGHIJKLMNOPQRSTUVXYZ0123456789!$";
    string passsword = string.Empty;
    Random random = new Random();

    for (int i = 0; i < lunghezza; i++)
    {
      char carattere = caratteri[random.Next(caratteri.Length)];

      if (random.Next(0, 2) == 1) { carattere = Char.ToLower(carattere); }

      passsword += carattere;
    }

    return passsword;
  }
}

and the JqueryClient Register Call:

$.ajax({
  type: 'POST',
  url: api_uri + 'users/register',
  data: JSON.stringify(_user),
  contentType: 'application/json'
})

I want to disable CORS Policy just for register and login web methods, so I added the [DisableCors] attribute to them.

I hosted the WebApi project on IIS (localhost:82) and the JqueryClient too (localhost:83).

When tried to call the register web method, I receveid an error of CORS failed parameters.

Chrome Console Debugger Error

Can someone help me resolve the problem?

  • 写回答

1条回答 默认 最新

  • weixin_33711647 2017-03-02 11:37
    关注

    If you DisableCors then you won't be able to make cross domain call on that action. In case you want to secure your service from cross domain calls then use EnableCors with restricted domain. Like you already doing at controller level

    [EnableCors(origins: "http://pincopalli.com,http://localhost:83", headers: "*", methods: "*")]
    

    This will allow calls only from http://pincopalli.com and http://localhost:83. Will reject calls from all other domain. Ex- http://localhost:84 or http://contoso.com etc..

    This will secure your api from cross domain call originating from domains you don't trust. Hope this helps.

    For more detail reading : https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api#allowed-origins

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题