【问题标题】:HttpClient 401 Unauthorized after PostAsync (Bearer Auth)PostAsync(承载身份验证)后 HttpClient 401 未经授权
【发布时间】:2019-02-27 14:44:12
【问题描述】:

我是新手,在我刚刚停留在帖子上之前从不使用 REST API,我不知道如何在 PostAsync 中获取代码 200。我做错了什么或我错过了什么?....

public async Task<ActionResult> Create([Bind(Include = "IndividualId,SolicitantDataView,TerminalId,OGPCorrelationID,OGPATGNumber,Source,UserId,SendByEmail")] RequestViewModel requestViewModel)
    {
        var token = await GetToken();
        RequestModel requestModel = new RequestModel(requestViewModel);
        string Baseurl = "https://exampleapiservice.com/api";

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(Baseurl);
            client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", token);
            var content2 = new FormUrlEncodedContent(new[]
           {
        new KeyValuePair<string, string>("IndividualId", requestViewModel.IndividualId),
        new KeyValuePair<string, string>("OGPATGNumber", requestViewModel.OGPATGNumber),
        new KeyValuePair<string, string>("OGPCorrelationID", requestViewModel.OGPCorrelationID),
        new KeyValuePair<string, string>("Source", requestViewModel.Source),
        new KeyValuePair<string, string>("UserId", requestViewModel.UserId),
        new KeyValuePair<string, string>("TerminalId", requestViewModel.TerminalId.ToString()),
        new KeyValuePair<string, string>("SendByEmail", requestViewModel.SendByEmail.ToString()),
        new KeyValuePair<string, string>("Name", requestViewModel.SolicitantDataView.Name),
        new KeyValuePair<string, string>("MiddleInitial", requestViewModel.SolicitantDataView.MiddleInitial),
        new KeyValuePair<string, string>("LastName", requestViewModel.SolicitantDataView.LastName),
        new KeyValuePair<string, string>("LastName2", requestViewModel.SolicitantDataView.LastName2),
        new KeyValuePair<string, string>("SSN", requestViewModel.SolicitantDataView.SSN),
        new KeyValuePair<string, string>("BirthDate", requestViewModel.SolicitantDataView.BirthDate.ToString()),
        new KeyValuePair<string, string>("EmailAddress", requestViewModel.SolicitantDataView.EmailAddress),
        new KeyValuePair<string, string>("DriverLicense", requestViewModel.SolicitantDataView.DriverLicense)

    });
            var myContent = JsonConvert.SerializeObject(content2);
            var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
            var byteContent = new ByteArrayContent(buffer);
            byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");



            HttpResponseMessage Res = await client.PostAsync("/api/getcertification ", byteContent);

}
        return View(requestModel);
    }

这是我需要填写的参数。我正在尝试在 Postman 中进行测试,但我从未使用过该应用程序。在 Postman 中添加这些参数的正确方法是什么??

{

"SolicitantData": null,

"DemographicalData": {

"Name": "Nombre",

"MiddleInitial": "I",

"LastName": "Apellido Paterno",

"LastName2": "Apellido Materno",

"NickName": "",

"SSN": "123456789",

"BirthDate": "19xx-xx-xx",

"EmailAddress": "email@somedomain.com",

"DriverLicense": "",

"DeathDate": "",

"Addresses": [],

"PhoneNumbers": []

}

【问题讨论】:

  • 你必须弄清楚为什么服务会返回它。
  • 您是否真的将Baseurl 保留为“https://”?还是你在里面放了一个真实的网址?
  • @Jonathan 您的代码不完整,您异步返回的实际 ActionResult 在哪里?
  • 您是否可以使用其他工具(Postman、SoapUI 等)发出有效请求
  • @ArturMustafin 我只是发布了给我错误的部分: HttpResponseMessage Res = await client.PostAsync(" ", byteContent);乔纳森说 BaseUrl 是一个例子,我有正确的例子。

标签: c# asp.net-mvc rest api


【解决方案1】:

您必须在令牌之前包含身份验证类型,因此您需要 替换这行代码以包含身份验证类型,例如Bearer

client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", token);

 client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", string.Format("Bearer {0}", token));

【讨论】:

  • 我实际上添加了一个我需要填写的参数示例,我认为我在 HttpClient 部分的代码中遗漏了其他内容。
  • 是的,现在和现在 var content2 =new FormUrlEncodedContent(new[] 向我抛出一个未设置为对象实例的对象引用。
  • 所以你通过了第一个授权问题?
  • 是的,我之前通过了 Auth 并通过了 content2 但现在有了这个更改,我无法使用 FormUrlEncodedContent。
  • 您在侧发布的数据中有一个值为 null 您必须对其进行调试并处理它
猜你喜欢
  • 2018-07-09
  • 1970-01-01
  • 2016-04-15
  • 2018-01-23
  • 1970-01-01
  • 2021-09-28
  • 2020-10-25
  • 2013-05-24
  • 2013-08-09
相关资源
最近更新 更多