javascript - 如何从 Windows 窗体应用程序调用 Web API 登录操作

标签 javascript c# winforms asp.net-web-api httpwebrequest

我有一个带有注册、登录和调用 API 模块的简单 Web 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);
}

我的 Controller Action 如下

 // 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 中使用以下代码来调用登录操作:

  HttpClient client = new HttpClient();

        Uri baseAddress = new Uri("https://localhost:44305/");

        client.BaseAddress = baseAddress;

        ArrayList paramList = new ArrayList();
        user u = new user();
        u.username = username;
        u.password = password;

        paramList.Add(u);


        HttpResponseMessage response = client.PostAsJsonAsync("api/product/SupplierAndProduct", paramList).Result;

在上面的代码中,我尝试调用 Controller 操作但失败了。为了实现我的目标,即使从 winform 应用程序调用 JavaScript 也可以。

最佳答案

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;

关于javascript - 如何从 Windows 窗体应用程序调用 Web API 登录操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38137817/

相关文章:

c# - 自动映射器可以处理某些属性不匹配的情况吗?

vb.net - “.ctor”不是有效标识符

javascript - 如何在 Google 开发者工具中查看字符串

javascript - 基本 JS 对象 {a :1, b :2} not supported in Nashorn?

c# - 从 DataGridView 返回不同值的列表

vb.net - 如何知道应用程序是从控制台还是资源管理器运行的?

C# 窗口在忙碌时变得空白 -> 进度条?但是怎么办?

javascript - JavaScript 中段落的 CSS 样式

javascript - 转换为数组

c# - C# EmguCV Image.setValue(...) 方法的 C++ OpenCV 等价物