从本地Web表单应用程序进行本地Web api调用

时间:2016-05-27 15:22:26

标签: jquery asp.net asp.net-web-api webforms asp.net-web-api2

我想知道是否可以拨打电话:

jQuery.ajax({
            type: "POST",
            url: "http://localhost:5832/api/Login",
            data: "{username: user1, password:'123456'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json", 
            success: function (data) {
                alert(data.d);
            }
        });

这基本上是对这个web api控制器的调用:

public class LoginController : ApiController
    {
        [System.Web.Http.AcceptVerbs("POST")]
        public HttpResponseMessage Post(string username, string password)
        {
            string authenticationToken = "";
            Helpers hpl = new Helpers();
            authenticationToken = hpl.LoginUser(username, password);
            int userId = 0;
            if (Int32.TryParse(authenticationToken, out userId))
            {
                bool isValidGame = false;
                ssqGame game = db.ssqGames.Where(s => s.userId == userId).FirstOrDefault();
                if (game.ssqGameId != 0)
                {
                    ssqLogin login = db.ssqLogins.FirstOrDefault(s => s.ssqGameId == game.ssqGameId);
                    if (login != null)
                    {
                        return Request.CreateResponse(HttpStatusCode.OK, "Token: " + login.authorizationToken, new JsonMediaTypeFormatter(), "application/json");
                    }
                    else
                    {
                        ssqLogin loginNew = new ssqLogin();
                        loginNew.ssqGameId = game.ssqGameId;
                        loginNew.login = DateTime.Now;
                        loginNew.activeState = 1;
                        loginNew.authorizationToken = hpl.RandomString(30);
                        db.ssqLogins.Add(loginNew);
                        db.SaveChanges();
                    }
                }
            }

            return Request.CreateResponse(HttpStatusCode.OK, authenticationToken);
        }
    }

jquery ajax调用来自另一个本地Web表单项目,该项目在不同的端口上运行:http://localhost:15528/test。我想知道是否有可能进行这样的调用,因为此时我无法触发该函数,在firebug中看到此错误:enter image description here

由于

1 个答案:

答案 0 :(得分:0)

是的,绝对有可能,您只需为您的网络API启用CORS,看一下这篇文章:

http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api