【问题标题】:Make local web api call from local web forms app从本地 Web 表单应用程序进行本地 Web api 调用
【发布时间】:2016-09-26 00:13:47
【问题描述】:

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

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 中看到此错误:

【问题讨论】:

  • 谢谢,请将其写为答案。它帮助了我。

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


【解决方案1】:

是的,绝对有可能,你只需为你的 web api 启用 CORS,看看这篇文章:

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

【讨论】:

    猜你喜欢
    • 2017-12-29
    • 1970-01-01
    • 2015-08-05
    • 2017-11-15
    • 2012-06-11
    • 2011-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多