调用web api时$ http调用两次

Jig*_*992 0 asp.net-mvc angularjs asp.net-web-api2

我创建了一个WEB API使用ASP.NET MVC WEB API 2.0.Web API包含像login,register等等方法.
AngularJS用来调用WEB API方法,但它调用了两次.例如,当我调用POST方法时,它首先调用OPTION(我没有创建任何OPTION方法),然后调用POST方法.
我的代码:(用于登录)
HTML:

<div class="container" ng-controller="UserAccount">
    <form ng-submit="loginNow(user)">
        <input type="email" placeholder="Enter Email" required ng-model="user.email" id="txtEmail" class="form-control" />
        <br />
        <input type="password" placeholder="Enter Password" required ng-model="user.password" id="txtPwd" class="form-control" />
        <br />
        <button type="submit" class="btn btn-primary">Login</button>
    </form>
</div>
Run Code Online (Sandbox Code Playgroud)


AngularJS控制器:

$scope.loginNow = function (user) {
        $http.post(rootURL + "login", { email: user.email, password: user.password })
            .success(function (data) {
                if (data.id > 0) {
                    sessionStorage.setItem('userid', data.id);
                    window.location = '/';
                }
            });
}
Run Code Online (Sandbox Code Playgroud)


WEB API:

public class UsersController : ApiController
    {
        private UserEntities db = new UserEntities();

        // GET: api/Users
        public IQueryable<Users_tbl> GetUsers_tbl()
        {
            return db.Users_tbl;
        }

        [ActionName("login")]
        public IHttpActionResult PostUser_Login(string email, string password)
        {
            int id = db.Users_tbl.Where(a => a.email == email && a.password == password).Select(a => a.id).SingleOrDefault();
            if(id <= 0)
            {
                return NotFound();
            }
            return Ok(id);
        }

        [ActionName("register")]
        public int PostUser_Register(string email, string password)
        {
            int id = db.Users_tbl.Where(a => a.email == email).Select(a => a.id).SingleOrDefault();
            if(id > 0)
            {
                return 1;
            }
            Users_tbl user = new Users_tbl();
            user.email = email;
            user.password = password;
            try
            {
                db.Users_tbl.Add(user);
                db.SaveChanges();
            }
            catch
            {
                return 2;
            }
            return 0;
        }


        // GET: api/Users/5
        [ResponseType(typeof(Users_tbl))]
        public IHttpActionResult GetUsers_tbl(int id)
        {
            Users_tbl users_tbl = db.Users_tbl.Find(id);
            if (users_tbl == null)
            {
                return NotFound();
            }

            return Ok(users_tbl);
        }


        // PUT: api/Users/5
        [ResponseType(typeof(void))]
        public IHttpActionResult PutUsers_tbl(int id, Users_tbl users_tbl)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != users_tbl.id)
            {
                return BadRequest();
            }

            db.Entry(users_tbl).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!Users_tblExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        [ActionName("profile")]
        // POST: api/Users
        [ResponseType(typeof(Users_tbl))]
        public IHttpActionResult PostUsers_tbl(Users_tbl users_tbl)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Users_tbl.Add(users_tbl);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = users_tbl.id }, users_tbl);
        }

        // DELETE: api/Users/5
        [ResponseType(typeof(Users_tbl))]
        public IHttpActionResult DeleteUsers_tbl(int id)
        {
            Users_tbl users_tbl = db.Users_tbl.Find(id);
            if (users_tbl == null)
            {
                return NotFound();
            }

            db.Users_tbl.Remove(users_tbl);
            db.SaveChanges();

            return Ok(users_tbl);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool Users_tblExists(int id)
        {
            return db.Users_tbl.Count(e => e.id == id) > 0;
        }
    }
Run Code Online (Sandbox Code Playgroud)

Adn*_*mer 7

这是浏览器的默认行为.在发送corss-domain AJAX调用之前,浏览器发送一个飞行前请求(OPTION请求)为什么?

这里查看如何最大限度地减少飞行前请求:

更新

如果您确实不想发送飞行前请求,可以选择不违反同源策略(SOP).可能的解决方案是:

JSONP:这是一种利用同源安全策略的HTML脚本元素异常的技术.脚本标记可以从其他域加载JavaScript,并且可以将查询参数添加到脚本URI,以将信息传递给托管脚本的服务器,以获取您希望访问的资源.JSONP服务器将返回在浏览器中评估的JavaScript,该浏览器调用页面上已经约定的JavaScript函数将服务器资源数据传递到您的页面.

服务器端代理:绕过同源策略执行跨域请求的另一种方法是根本不做任何跨域请求!如果您使用驻留在域中的代理,则只需使用此代码从后端代码访问外部服务,并将结果转发到客户端代码.由于请求代码和代理位于同一域中,因此不会违反SOP.

更新 您可以从Web API 2响应OPTIONS请求,这样就不会抛出405或404.请查看此处/sf/answers/2619802251/