2

我正在构建一个访问 Maximo Rest API 的应用程序,这是我用来调用 API 的代码。

我正在使用 .NET Framework 4.5 C#

public class MaximoClient
{

    private string ServerURL;
    private string AuthUsername;
    private string AuthPassword;
    private CookieContainer cookieContainer = null;

    private string HttpGetRequest(string URL)
    {
        string ResponseContent;
        try
        {
            if (this.cookieContainer == null)
            {
                this.Authenticate();
            }


            HttpClientHandler handler = new HttpClientHandler
            {
                CookieContainer = this.cookieContainer
            };
            HttpClient client = new HttpClient(handler);

            HttpRequestMessage Request = new HttpRequestMessage
            {
                RequestUri = new Uri(URL, UriKind.Absolute),
                Method = HttpMethod.Get
            };


            var Response = client.SendAsync(Request).Result;
            ResponseContent = Response.Content.ReadAsStringAsync().Result;
        }
        catch (Exception e)
        {
            throw e;
        }

        return ResponseContent;
    }



    private void Authenticate()
    {
        try
        {
            this.cookieContainer = new CookieContainer();
            HttpClientHandler handler = new HttpClientHandler
            {
                CookieContainer = cookieContainer,
                AllowAutoRedirect = false,
                UseCookies = true,

            };

            this.Client = new HttpClient(handler);

            HttpClient client = this.Client;

            HttpRequestMessage Request = new HttpRequestMessage
            {
                RequestUri = new Uri($"{this.ServerURL}/oslc/j_security_check", UriKind.Absolute),
                Method = HttpMethod.Post
            };
            var postData = Encoding.ASCII.GetBytes($"j_username={this.AuthUsername}&j_password={this.AuthPassword}");
            Request.Content = new ByteArrayContent(postData);
            Request.Content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");


            HttpResponseMessage Response = client.SendAsync(Request).Result;

            string ResponseContent = Response.Content.ReadAsStringAsync().Result;

            int code = (int)Response.StatusCode;
            if (code > 399)
            {
                throw new Exception("HttpWebRequest returned Status Code:" + Response.StatusCode + " : " + Response.ReasonPhrase);
            }
        }
        catch (Exception e)
        {
            throw e;
        }
    }

}

如您所见,我正在使用 cookie 容器来捕获身份验证时随响应发送的 cookie。Authenticate() 有效。它返回一个带有 LTPA 令牌的 302。但是 GET 请求失败。我收到此错误:

用于登录的 LTPA 令牌无效。启用 WebSphere Application Server 安全性时,LTPA 令牌用于登录过程。等待几秒钟,然后再次尝试登录。如果问题仍然存在,请清除浏览器 cookie 或重新启动浏览器

我在使用 Postman 时遇到了类似的错误,但是当我再次尝试请求时,它可以工作。

我切换了框架并使用了 .NET Core 2.1。完全相同的代码可以正常工作。

为什么这适用于 .NET Core 而不是 .NET 框架?使用 .NET 核心不能解决我的问题,它需要 .NET 4.5。谁能帮我这个?

4

0 回答 0