Make local web api call from local web forms app

柔情痞子 提交于 2019-12-11 12:43:25

问题


I want to know if its possible to make this call:

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

Which is basically call to this web api controller:

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

The jQuery ajax call is from another local web forms project which is running on a different port: http://localhost:15528/test. I want to know if its possible to make calls such as this one because I'm not able to trigger the function at this moment, seeing this error in Firebug:


回答1:


Yes, definitely possible, you just enable CORS for your web api, take a look this article:

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



来源:https://stackoverflow.com/questions/37487141/make-local-web-api-call-from-local-web-forms-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!