使本地Web API调用本地Web窗体应用程序 [英] make local web api call from local web forms app

查看:429
本文介绍了使本地Web API调用本地Web窗体应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,如果它可能使这一呼吁:

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

这基本上是调用此Web API控制器:

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

jQuery的AJAX调用是从在不同端口上运行的其他本地网络形式的项目:的http://本地主机:15528 /测试。我想知道,如果它能够拨打电话,如这一个,因为我不能在这个时候触发功能,在萤火看到此错误:的

The jquery ajax call is from another local web forms project which is running on a different port:

感谢

推荐答案

是的,绝对有可能,你只要启用您的Web API CORS,看看这篇文章:

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

这篇关于使本地Web API调用本地Web窗体应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆