HttpClient 401 не авторизован после PostAsync (аутентификация на предъявителя) - PullRequest
0 голосов
/ 25 февраля 2019

Я новичок в этом, никогда не использую REST API, пока я не застрял на посте, я не знаю, как получить код 200 в PostAsync.Что я делаю не так или что мне не хватает? ....

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);
    }

Это параметры, которые мне нужно заполнить.Я пытаюсь проверить в Почтальоне, но я никогда не использую это приложение.Как правильно добавить эти параметры в Почтальон ??

{

"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": []

}

1 Ответ

0 голосов
/ 26 февраля 2019

вы должны включить тип аутентификации перед токеном, поэтому вам нужно заменить эту строку кода на тип аутентификации, например Bearer

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

на

 client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", string.Format("Bearer {0}", token));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...