来自Windows窗体应用程序的ASP.NET身份验证

4
我在谷歌上搜索了“Windows窗体应用程序中的ASP.NET身份验证”,但结果是“使用ASP.NET进行Windows身份验证”,这不是我要找的。
场景: 我有一个ASP.NET应用程序和一组WCF服务,通过AJAX调用向应用程序提供数据。这些WCF服务需要ASP.NET身份验证,在浏览器中没问题,因为有一个cookie提供身份验证信息,或者通过登录页面要求用户进行身份验证。
我需要从Windows窗体应用程序调用这些服务,而不改变它们的工作方式。也就是说,Windows窗体应用程序将接收来自服务的JSON数据并处理它。
问题: 我需要在使用WCF服务之前进行身份验证,但由于这不是Web应用程序,所以没有cookie,并且无法显示登录页面!
问题: 如何从Windows窗体应用程序向ASP.NET Web应用程序提供身份验证?
1个回答

5

您需要像浏览器一样为每个请求存储cookie。当您发送登录表单的请求时,cookie变量会保持您的身份验证状态,以便后续的请求也可以通过身份验证。

static class Requester
{
    static CookieContainer cookieJar = new CookieContainer();
    static string userAgent = ""; //specify your user agent

    /// <summary>
    /// Static method to request a web page. 
    /// It acts like a browser which means that keeps all cookies for depending domain.
    /// </summary>
    /// <param name="URL"></param>
    /// <returns></returns>
    static public FinalResponse sendRequest(string URL)
    {
        return sendRequest(URL, "");
    }


    static public FinalResponse sendRequest(string URL, string parameters)
    {
        FinalResponse result = new FinalResponse();
        Stopwatch timer = new Stopwatch();
        HttpWebRequest request;

        try
        {
            request = (HttpWebRequest)HttpWebRequest.Create(URL);
            request.Referer = "http://google.com"; //specify your referer
            request.CookieContainer = cookieJar;
            request.UserAgent = userAgent;
            BugFix_CookieDomain();
            request.AllowAutoRedirect = true;
            if (parameters != "")
            {
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = parameters.Length;

                //push parameters to request stream
                StreamWriter myWriter = new StreamWriter(request.GetRequestStream());
                myWriter.Write(parameters);
                myWriter.Close();
            }
            //send request
            result.requestTime = DateTime.Now;
            timer.Start();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            timer.Stop();
            result.responseMilliseconds = timer.ElapsedMilliseconds;
            BugFix_CookieDomain();
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                result.document = sr.ReadToEnd();
                sr.Close();
                result.isSucceded = true;
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            result.document = "";
            result.isSucceded = false;
        }
        return result;
    }


    /// <summary>
    /// Call this function before all usage of cookieJar. 
    /// It fixes the bug (!) of CookieContainer Class. 
    /// </summary>
    private static void BugFix_CookieDomain()
    {
        System.Type _ContainerType = typeof(CookieContainer);
        Hashtable table = (Hashtable)_ContainerType.InvokeMember("m_domainTable",
                                   System.Reflection.BindingFlags.NonPublic |
                                   System.Reflection.BindingFlags.GetField |
                                   System.Reflection.BindingFlags.Instance,
                                   null,
                                   cookieJar,
                                   new object[] { });
        ArrayList keys = new ArrayList(table.Keys);
        foreach (string keyObj in keys)
        {
            string key = (keyObj as string);
            if (key[0] == '.')
            {
                string newKey = key.Remove(0, 1);
                table[newKey] = table[keyObj];
            }
        }
    }

不错的例子。唯一缺少的是在cookieContainer中修复代码的bug的引用 - 这样我们才知道您实际上正在解决什么问题以及该bug是否仍然存在。 - beterthanlife
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Can Guney Aksakalli

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接