简体   繁体   English

为什么我的 Web api 在使用 WebClient 类时返回状态代码 401,而在使用 HttpWebResponse 时返回状态代码 200?

[英]Why my web api return Status code 401 when i use WebClient class and Status code 200 when i use HttpWebResponse?

So i am fairly new to this word, so excuse me if i am missing something.所以我对这个词很陌生,所以如果我遗漏了什么,请原谅。

I've wrote a Web Api in Asp.Net.Core 2.2 which use jwt token for authorizazion.我在 Asp.Net.Core 2.2 中编写了一个 Web Api,它使用 jwt 令牌进行授权。 My Authenticate method looks like this:我的 Authenticate 方法如下所示:

    [AllowAnonymous]
    [HttpGet("auth")]
    public ActionResult<SecurityToken> Auth([FromHeader] string identity)
    {
        // authentication successful so generate jwt token
        //if (HwKeyManager.MASTER_KEY.KEY_NOT_PRESENT)
        //{
        //    //hasLicense = HwKeyManager.product_license_get();
        //}
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes(someKey);
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.Name, identity)
            }),
            Expires = DateTime.Now.AddMinutes(10),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
        };
        try
        {
            SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
            string returnToken = tokenHandler.WriteToken(token);
            return Ok(returnToken);
        }
        catch(Exception ex)
        {
            logger.Error("Error while creating token : " + ex.Message);
            return StatusCode(500);
        }
    }

this works and give me a token which i used with success in a request like the following:这有效并给了我一个令牌,我在如下请求中成功使用了它:

 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "status");
 request.Timeout = 15000;
 request.Headers.Add("Authorization", "Bearer " + token);
 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
 {
    if (response.StatusCode == HttpStatusCode.OK)
    {
       return true;
    }
    else
    {
       return false;
    }

 }

However for another method i was trying to use the WebClient class to create a POST request, but for the life of me i can't make the following piece of code to work (i get a 401 status code, Unauthorized)然而,对于另一种方法,我试图使用 WebClient 类来创建 POST 请求,但在我的一生中,我无法使以下代码起作用(我得到 401 状态代码,未经授权)

WebClient wcl = new WebClient();
wcl.Headers.Add(HttpRequestHeader.ContentType, "application/json");
wcl.Headers.Add("Authorization", "Bearer" + token);
wcl.Encoding = System.Text.Encoding.UTF8;
string pippo = wcl.UploadString(url + "doSomething", "POST", Data.ToJson());

if i switch to HttpWebResponse however everything work如果我切换到 HttpWebResponse 但是一切正常

byte[] bytes = Encoding.ASCII.GetBytes(Data.ToJson());
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "doSomething");
request.Timeout = 15000;
request.Headers.Add("Authorization", "Bearer " + token);
request.Method = "POST";
request.ContentType = "application/json";
Stream dataStream = request.GetRequestStream();
dataStream.Write(bytes, 0, bytes.Length);
dataStream.Close();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    if (response.StatusCode == HttpStatusCode.OK)
    {

    }
    else
    {

    }

}

Can someone clarify me why this happen and if there is a way to solve it?有人可以澄清我为什么会发生这种情况以及是否有办法解决它?

You have forgoten a space between bearer.你忘记了承载者之间的空间。

wcl.Headers.Add("Authorization", "Bearer" + token);

So just change it to this所以把它改成这个

wcl.Headers.Add("Authorization", "Bearer " + token);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C# REST Api 在我通过 HttpClient 调用 ZDB974238714CA8DE634ACEClient 时总是返回 401 状态码 - C# REST Api always return 401 status code when i am calling API by HttpClient 当我在winforms C#中使用web api 发布数据时的状态码200 - Status code 200 when i post data using web api in winforms C# 在Web应用程序中使用类时,出现字符不清晰的HttpWebResponse - I get HttpWebResponse with unclear characters when use a class in web application 如果状态码不等于 200 OK 使用 Polly 重试 api 请求 - Use Polly to retry api request if the status code is not equal to 200 OK 我应该返回状态代码还是在.Net Web Api 2中抛出异常 - Should I return a status code or throw an exception in .Net Web Api 2 发生异常时,Web Api始终返回http状态代码200 - Web Api always returns http status code 200 when an exception occurs 如何将HTTP状态代码从Web API中的方法返回给main? - How do I return the HTTP Status Code from a method in my Web API to main? 如何获取发布到我的Web API的状态代码 - How can I get the status code of a post to my web api HttpWebResponse 状态码 429 - HttpWebResponse Status Code 429 为什么(HttpWebResponse)request.GetResponse()方法返回错误页面的状态码200? - why (HttpWebResponse)request.GetResponse() method returning status code 200 for Error Page?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM