Javascript 如何从Windows窗体应用调用web API登录操作

Javascript 如何从Windows窗体应用调用web API登录操作,javascript,c#,winforms,asp.net-web-api,httpwebrequest,Javascript,C#,Winforms,Asp.net Web Api,Httpwebrequest,我有一个简单的web API,带有注册、登录和调用API模块。我想从Windows窗体应用程序调用每个功能 在web API中,我使用JavaScript中的以下脚本调用登录方法: self.login = function () { self.result(''); var loginData = { grant_type: 'password', username: self.loginEmail(), password:

我有一个简单的web API,带有注册、登录和调用API模块。我想从Windows窗体应用程序调用每个功能

在web API中,我使用JavaScript中的以下脚本调用登录方法:

 self.login = function () {
    self.result('');

    var loginData = {
        grant_type: 'password',
        username: self.loginEmail(),
        password: self.loginPassword()
    };

    $.ajax({
        type: 'POST',
        url: '/Token',
        data: loginData
    }).done(function (data) {
        self.user(data.userName);
        // Cache the access token in session storage.
        sessionStorage.setItem(tokenKey, data.access_token);
    }).fail(showError);
}
我的控制器操作如下

 // POST api/Account/AddExternalLogin
    [Route("AddExternalLogin")]
    public async Task<IHttpActionResult> AddExternalLogin(AddExternalLoginBindingModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

        AuthenticationTicket ticket = AccessTokenFormat.Unprotect(model.ExternalAccessToken);

        if (ticket == null || ticket.Identity == null || (ticket.Properties != null
            && ticket.Properties.ExpiresUtc.HasValue
            && ticket.Properties.ExpiresUtc.Value < DateTimeOffset.UtcNow))
        {
            return BadRequest("External login failure.");
        }

        ExternalLoginData externalData = ExternalLoginData.FromIdentity(ticket.Identity);

        if (externalData == null)
        {
            return BadRequest("The external login is already associated with an account.");
        }

        IdentityResult result = await UserManager.AddLoginAsync(User.Identity.GetUserId(),
            new UserLoginInfo(externalData.LoginProvider, externalData.ProviderKey));

        if (!result.Succeeded)
        {
            return GetErrorResult(result);
        }

        return Ok();
    }

    // POST api/Account/RemoveLogin
    [Route("RemoveLogin")]
    public async Task<IHttpActionResult> RemoveLogin(RemoveLoginBindingModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        IdentityResult result;

        if (model.LoginProvider == LocalLoginProvider)
        {
            result = await UserManager.RemovePasswordAsync(User.Identity.GetUserId());
        }
        else
        {
            result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(),
                new UserLoginInfo(model.LoginProvider, model.ProviderKey));
        }

        if (!result.Succeeded)
        {
            return GetErrorResult(result);
        }

        return Ok();
    }

    // GET api/Account/ExternalLogin
    [OverrideAuthentication]
    [HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)]
    [AllowAnonymous]
    [Route("ExternalLogin", Name = "ExternalLogin")]
    public async Task<IHttpActionResult> GetExternalLogin(string provider, string error = null)
    {
        if (error != null)
        {
            return Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error));
        }

        if (!User.Identity.IsAuthenticated)
        {
            return new ChallengeResult(provider, this);
        }

        ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);

        if (externalLogin == null)
        {
            return InternalServerError();
        }

        if (externalLogin.LoginProvider != provider)
        {
            Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            return new ChallengeResult(provider, this);
        }

        ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
            externalLogin.ProviderKey));

        bool hasRegistered = user != null;

        if (hasRegistered)
        {
            Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

             ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
                OAuthDefaults.AuthenticationType);
            ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
            Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
        }
        else
        {
            IEnumerable<Claim> claims = externalLogin.GetClaims();
            ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
            Authentication.SignIn(identity);
        }

        return Ok();
    }

    // GET api/Account/ExternalLogins?returnUrl=%2F&generateState=true
    [AllowAnonymous]
    [Route("ExternalLogins")]
    public IEnumerable<ExternalLoginViewModel> GetExternalLogins(string returnUrl, bool generateState = false)
    {
        IEnumerable<AuthenticationDescription> descriptions = Authentication.GetExternalAuthenticationTypes();
        List<ExternalLoginViewModel> logins = new List<ExternalLoginViewModel>();

        string state;

        if (generateState)
        {
            const int strengthInBits = 256;
            state = RandomOAuthStateGenerator.Generate(strengthInBits);
        }
        else
        {
            state = null;
        }

        foreach (AuthenticationDescription description in descriptions)
        {
            ExternalLoginViewModel login = new ExternalLoginViewModel
            {
                Name = description.Caption,
                Url = Url.Route("ExternalLogin", new
                {
                    provider = description.AuthenticationType,
                    response_type = "token",
                    client_id = Startup.PublicClientId,
                    redirect_uri = new Uri(Request.RequestUri, returnUrl).AbsoluteUri,
                    state = state
                }),
                State = state
            };
            logins.Add(login);
        }

        return logins;
    }

在上面的代码中,我尝试调用控制器操作,但失败了。为了实现我的目标,甚至从winform应用程序调用JavaScript都可以。

在类似您的情况下,我通常使用
HttpWebRequest
httpwebresponse

HttpClient client = new HttpClient();
Uri baseAddress = new Uri("http://localhost:2939/");
client.BaseAddress = baseAddress;

ArrayList paramList = new ArrayList();
Product product = new Product { ProductId = 1, Name = "Book", Price = 500, Category = "Soap" };
Supplier supplier = new Supplier { SupplierId = 1, Name = "AK Singh",     Address = "Delhi" };
paramList.Add(product);
paramList.Add(supplier);

HttpResponseMessage response = client.PostAsJsonAsync("api/product/SupplierAndProduct", paramList).Result;
//POST
var httpWebRequest = (HttpWebRequest)WebRequest.Create("path/api");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = WebRequestMethods.Http.Post;
httpWebRequest.Accept = "application/json; charset=utf-8";
//probably have to be added
//httpWebRequest.ContentLength = json.Length;

//do request
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    //write post data
    //also you can serialize yours objects by JavaScriptSerializer
    streamWriter.Write(json);
    streamWriter.Flush();
}

//get responce
using (var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
    //read
    using (Stream stream = httpResponse.GetResponseStream())
    {
        using (StreamReader re = new StreamReader(stream))
        {
            String jsonResponce = re.ReadToEnd();
        }
    }
}

//GET
var httpWebRequest = (HttpWebRequest)WebRequest.Create("path/api");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json; charset=utf-8";

//get responce
using (var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
    //read
    using (Stream stream = httpResponse.GetResponseStream())
    {
        using (StreamReader re = new StreamReader(stream))
        {
            String jsonResponce = re.ReadToEnd();
        }
    }
}

你也应该读这篇

下面的答案对你很有帮助


出现一个错误,提示httpclint不包含PostAsjSyncy的定义,在代码中,您没有在api url中指定控制器名称和方法名称。请检查我的api url
//POST
var httpWebRequest = (HttpWebRequest)WebRequest.Create("path/api");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = WebRequestMethods.Http.Post;
httpWebRequest.Accept = "application/json; charset=utf-8";
//probably have to be added
//httpWebRequest.ContentLength = json.Length;

//do request
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    //write post data
    //also you can serialize yours objects by JavaScriptSerializer
    streamWriter.Write(json);
    streamWriter.Flush();
}

//get responce
using (var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
    //read
    using (Stream stream = httpResponse.GetResponseStream())
    {
        using (StreamReader re = new StreamReader(stream))
        {
            String jsonResponce = re.ReadToEnd();
        }
    }
}

//GET
var httpWebRequest = (HttpWebRequest)WebRequest.Create("path/api");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json; charset=utf-8";

//get responce
using (var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
    //read
    using (Stream stream = httpResponse.GetResponseStream())
    {
        using (StreamReader re = new StreamReader(stream))
        {
            String jsonResponce = re.ReadToEnd();
        }
    }
}
        //GET
        var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://160.114.10.17:85/api/Inventory/GetProcessDataByProcessName?deviceCode=OvCHY1ySowF4T2bb8HdcYA==&processName=Main Plant");
        httpWebRequest.ContentType = "text/json";
        httpWebRequest.Method = WebRequestMethods.Http.Get;
        httpWebRequest.Accept = "application/json; charset=utf-8";

        //get responce
        using (var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse())
        {
            //read
            using (Stream stream = httpResponse.GetResponseStream())
            {
                using (StreamReader re = new StreamReader(stream))
                {
                    String jsonResponce = re.ReadToEnd();
                }
            }
        }