i am trying to search code through some project, i didnt succeed to recieve a proper response.
that what i did:
public async void GetProjects()
{
try
{
var personalaccesstoken = "mypersonalPat";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", personalaccesstoken))));
var httpClient = new HttpClient();
var list = new List<KeyValuePair<string, string>>();
list.Add(new KeyValuePair<string, string>("searchText", "a"));
list.Add(new KeyValuePair<string, string>("$top", "10"));
var content = new FormUrlEncodedContent(list);
var response = await httpClient.PostAsync("https://almsearch.dev.azure.com/myorganization/myproject/_apis/search/codesearchresults?api-version=5.1-preview.1", content);
var res = await response.Content.ReadAsStringAsync();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
in the response i got 203 status message, in the res i got this (formatted as XML):
Azure DevOps Services | Sign In var __vssPageContext = {"webContext":{"user":{"id":"aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa","name":"Anonymous","email":"","uniqueName":"TEAM FOUNDATION\\Anonymous"},"host":{"id":"7d0cc8e9-39e8-4313-9ff3-23ace0f8f4cf","name":"TEAM FOUNDATION","uri":"https://spsprodweu4.vssps.visualstudio.com/","relativeUri":"/","hostType":"deployment","scheme":"https","authority":"spsprodweu4.vssps.visualstudio.com"}},"moduleLoaderConfig":{"baseUrl":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/","paths":{"Profile/Scripts/Resources":"en-US","VSS/Resources":"en-US","Account/Scripts/Resources":"en-US","UserManagement/Scripts/Resources":"en-US","Authentication/Scripts/Resources":"en-US"},"map":{},"contributionPaths":{"VSS":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/VSS","pathType":"default"},"VSS/Resources":{"value":"en-US","pathType":"resource"},"q":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/q","pathType":"default"},"knockout":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/knockout","pathType":"default"},"mousetrap":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/mousetrap","pathType":"default"},"mustache":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/mustache","pathType":"default"},"react":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/react.15.3","pathType":"default"},"react-dom":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/react-dom.15.3","pathType":"default"},"react-transition-group":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/react-transition-group.15.3","pathType":"default"},"jQueryUI":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/jQueryUI","pathType":"default"},"jquery":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/jquery","pathType":"default"},"OfficeFabric":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/OfficeFabric","pathType":"default"},"tslib":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/tslib","pathType":"default"},"#uifabric":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/#uifabric","pathType":"default"},"VSSUI":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/VSSUI","pathType":"default"}},"shim":{"jquery":{"deps":[],"exports":"jQuery"}},"waitSeconds":30},"coreReferences":{"stylesheets":[{"url":"/_static/tfs/M166_20200303.4/_cssbundles/Default/vss-bundle-ext-core-css-vgEHbWqZ4eb0vmOdl2cWjkpPtqcsX1GJCq4DnY78oN3s=","highContrastUrl":null,"isCoreStylesheet":true}],"scripts":[{"identifier":"JQuery","url":"/_static/3rdParty/_scripts/jquery-2.2.4.min.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},{"identifier":"JQueryXDomain","url":"/_static/3rdParty/_scripts/jquery.xdomainrequest.min.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},{"identifier":"Promise","url":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/promise.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},{"identifier":"GlobalScripts","url":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/global-scripts.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},{"identifier":"LoaderFixes","url":"/_static/tfs/M166_20200303.4/_scripts/TFS/pre-loader-shim.min.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":false},{"identifier":"AMDLoader","url":"/_static/3rdParty/_scripts/require.min.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},{"identifier":"LoaderFixes","url":"/_static/tfs/M166_20200303.4/_scripts/TFS/post-loader-shim.min.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":false}],"coreScriptsBundle":{"identifier":"CoreBundle","url":"/_public/_Bundling/Content?bundle=vss-bundle-basejs-v9GpWWBnsWqhM23ijhK2HfAqLowTXGUqZLDRsBCZbkfY=","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},"extensionCoreReferences":{"identifier":"CoreBundle","url":"/_public/_Bundling/Content?bundle=vss-bundle-ext-core-vjMBLvR7Lq0Z_oS-OpRMsP9FOHhkdmDXf0mCbsK5c0RI=","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true}},"webAccessConfiguration":{"isHosted":true,"paths":{"rootPath":"/","staticContentRootPath":"/","staticContentVersion":"M166_20200303.4","resourcesPath":"/_static/tfs/M166_20200303.4/_content/","staticRootTfs":"/_static/tfs/M166_20200303.4/","cdnFallbackStaticRootTfs":"/_static/tfs/M166_20200303.4/","staticRoot3rdParty":"/_static/3rdParty/"},"api":{"webApiVersion":"1","areaPrefix":"_","controllerPrefix":""},"mailSettings":{"enabled":false},"registryItems":{}},"microsoftAjaxConfig":{"cultureInfo":{"name":"en-US","numberFormat":{"CurrencyDecimalDigits":2,"CurrencyDecimalSeparator":".","IsReadOnly":true,"CurrencyGroupSizes":[3],"NumberGroupSizes":[3],"PercentGroupSizes":[3],"CurrencyGroupSeparator":",","CurrencySymbol":"$","NaNSymbol":"NaN","CurrencyNegativePattern":0,"NumberNegativePattern":1,"PercentPositivePattern":1,"PercentNegativePattern":1,"NegativeInfinitySymbol":"-∞","NegativeSign":"-","NumberDecimalDigits":2,"NumberDecimalSeparator":".","NumberGroupSeparator":",","CurrencyPositivePattern":0,"PositiveInfinitySymbol":"∞","PositiveSign":"+","PercentDecimalDigits":2,"PercentDecimalSeparator":".","PercentGroupSeparator":",","PercentSymbol":"%","PerMilleSymbol":"‰","NativeDigits":["0","1","2","3","4","5","6","7","8","9"],"DigitSubstitution":1},"dateTimeFormat":{"AMDesignator":"AM","Calendar":{"MinSupportedDateTime":"0001-01-01T00:00:00","MaxSupportedDateTime":"9999-12-31T23:59:59.9999999","AlgorithmType":1,"CalendarType":1,"Eras":[1],"TwoDigitYearMax":2029,"IsReadOnly":true},"DateSeparator":"/","FirstDayOfWeek":0,"CalendarWeekRule":0,"FullDateTimePattern":"dddd, MMMM d, yyyy h:mm:ss tt","LongDatePattern":"dddd, MMMM d, yyyy","LongTimePattern":"h:mm:ss tt","MonthDayPattern":"MMMM d","PMDesignator":"PM","RFC1123Pattern":"ddd, dd MMM yyyy HH':'mm':'ss 'GMT'","ShortDatePattern":"M/d/yyyy","ShortTimePattern":"h:mm tt","SortableDateTimePattern":"yyyy'-'MM'-'dd'T'HH':'mm':'ss","TimeSeparator":":","UniversalSortableDateTimePattern":"yyyy'-'MM'-'dd HH':'mm':'ss'Z'","YearMonthPattern":"MMMM yyyy","AbbreviatedDayNames":["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],"ShortestDayNames":["Su","Mo","Tu","We","Th","Fr","Sa"],"DayNames":["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],"AbbreviatedMonthNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthNames":["January","February","March","April","May","June","July","August","September","October","November","December",""],"IsReadOnly":true,"NativeCalendarName":"Gregorian Calendar","AbbreviatedMonthGenitiveNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthGenitiveNames":["January","February","March","April","May","June","July","August","September","October","November","December",""]},"numberShortForm":{"QuantitySymbols":["K","M","B"],"NumberGroupSize":1000,"ThousandSymbol":"K"},"eras":null}},"timeZonesConfiguration":{},"featureAvailability":{"featureStates":{"VisualStudio.Services.Contribution.EnableOnPremUnsecureBrowsers":false,"VisualStudio.Service.WebPlatform.ClientErrorReporting":false,"Microsoft.VisualStudio.Services.Gallery.Client.UseCdnAssetUri":false,"VisualStudio.Services.WebAccess.SubresourceIntegrity":false,"VisualStudio.Services.IdentityPicker.ReactProfileCard":true}},"appInsightsConfiguration":{"enabled":false,"instrumentationKey":"00000000-0000-0000-0000-000000000000","insightsScriptUrl":null},"diagnostics":{"sessionId":"24ec3e5b-2a51-44d0-8738-32e2f2c48c12","activityId":"24ec3e5b-2a51-44d0-8738-32e2f2c48c12","bundlingEnabled":true,"webPlatformVersion":"M166","serviceVersion":"Dev18.M166.1 (build: AzureDevOps_M166_20200320.5)"},"navigation":{"topMostLevel":"deployment","area":"","currentController":"Signin","currentAction":"Index","routeId":"LegacyWebAccessRoute","routeValues":{"controller":"Signin","action":"Index"}},"globalization":{"explicitTheme":"","theme":"Default","culture":"en-US","timezoneOffset":0,"timeZoneId":"UTC"},"serviceInstanceId":"951917ac-a960-4999-8464-e3f0aa25b381","hubsContext":{},"serviceLocations":{"locations":{"951917ac-a960-4999-8464-e3f0aa25b381":{"Application":"https://spsprodweu4.vssps.visualstudio.com/","Deployment":"https://spsprodweu4.vssps.visualstudio.com/"}}}}; var __cultureInfo = __vssPageContext.microsoftAjaxConfig.cultureInfo;
hope someone can tell me the proper way to send the post request.
Try with below script:
try
{
var personalaccesstoken = "{token}";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", personalaccesstoken))));
var httpClient = new HttpClient();
var newcontent = new StringContent("{\"searchText\":\"gradle\",\"$top\":33}", Encoding.UTF8, "application/json");
using (HttpResponseMessage response = await client.PostAsync("https://almsearch.dev.azure.com/{org}/{project}/_apis/search/codesearchresults?api-version=5.1-preview.1", newcontent))
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Result:
I need to add two header of Authorization in HttpClient as below:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "XYZNQVJJTkFQUDpX...=");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwToken);
But it seems the last one will override the first one.
I need the Basic and Bearer token. Bearer token for me to pass through the Proxy server which host the SAP WebService, the Basic token for the SAP server. In this case, what I should do?
Update:
How to compose 2 HttpRequestMessage?
string webServiceUrl = "https://adfs.xxx.xxx/";
string strURL = "https://xxx.xxx.xxx/";
HttpResponseMessage responseMessage;
HttpClient client = new HttpClient();
//--1st HttpRequestMessage
var tokenRequest = new HttpRequestMessage(HttpMethod.Post, strURL);
tokenRequest.Headers.Authorization = new AuthenticationHeaderValue("Basic", "XYZNQVJJTkFQUDpX...=");
HttpContent httpContent = new FormUrlEncodedContent(
new[]
{
new KeyValuePair<string, string>("grant_type", "xxx"),
new KeyValuePair<string, string>("client_id", "xxx"),
new KeyValuePair<string, string>("scope", "xxx"),
new KeyValuePair<string, string>("assertion", Base64Assertion)
});
tokenRequest.Content = httpContent;
var tokenResponseMessage = await client.SendAsync(tokenRequest);
var token = await tokenResponseMessage.Content.ReadAsStringAsync();
//-- 2nd HttpRequestMessage
var serviceRequest = new HttpRequestMessage(HttpMethod.Get, webServiceUrl);
serviceRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var serviceResponseMessage = await client.SendAsync(serviceRequest);
In this case, what I should do?
You will need two separate clients, each with their own default authorization header,
client1.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "XYZNQVJJTkFQUDpX...=");
client2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwToken);
or one client with no default and the authorization set per request.
For example
var tokenRequest = new HttpRequestMessage(HttpMethod.Post, authServerUrl);
tokenRequest.Headers.Authorization = new AuthenticationHeaderValue("Basic", "XYZNQVJJTkFQUDpX...=");
var httpContent = new FormUrlEncodedContent(
new[]
{
new KeyValuePair<string, string>("grant_type", "xxx"),
new KeyValuePair<string, string>("client_id", "xxx"),
new KeyValuePair<string, string>("scope", "xxx"),
new KeyValuePair<string, string>("assertion",Base64Assertion)
});
tokenRequest.Content = httpContent;
var tokenResponseMessage = await client.SendAsync(tokenRequest);
var token = await responseMessage.Content.ReadAsStringAsync();
var serviceRequest = new HttpRequestMessage(HttpMethod.Get, webServiceUrl);
serviceRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var serviceResponseMessage = await client.SendAsync(serviceRequest);
//...
It has to do more with HTTP.Its not possible to send through multiple Authentication headers