I am sending an httpclient request as below. I want to send a parameter with a get request. How can I do that ? Or how can I use it properly?
For example; http://localhost:3000/users?business_code=123
using System.Net.Http;
using System;
using System.Threading.Tasks;
using MyApplication.Models;
namespace MyApplication.Api
{
public class ModelsRepository
{
public HttpClient _client;
public HttpResponseMessage _response;
public HttpRequestMessage _request;
public ModelsRepository()
{
_client = new HttpClient();
_client.BaseAddress = new Uri("http://localhost:3000/");
_client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImZ0aG1seW16QGhvdG1haWwuY29tIiwidXNlcklkIjoxLCJpYXQiOjE2MTM5NzI1NjcsImV4cCI6MTYxNDE0NTM2N30.-EVUg2ZmyInOLBx3YGzLcWILeYzNV-svm8xJiN8AIQI");
_client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<UsersModel> GetList()
{
_response = await _client.GetAsync($"users");
var json = await _response.Content.ReadAsStringAsync();
var listCS = UsersModel.FromJson(json);
return listCS;
}
}
}
What exactly do you mean by "you have to send the variable as a parameter"? Does it mean you want to add parameters dynamically by number and name?
In this case you could have e.g. a Dictionary as input and convert it into a query string:
var queryParameters = new Dictionary<string, string>
{
{ "business_code", "123" },
{ "someOtherParam", "456"}
};
var dictFormUrlEncoded = new FormUrlEncodedContent(queryParameters);
var queryString = await dictFormUrlEncoded.ReadAsStringAsync();
var response = await _client.GetAsync($"users?{queryString}")
Related
I am new to RestAPI and am not sure how to call one and pass it credentials. I have a Windows Forms with a "POST" button. This project is built using .Net framework 4.5. When user clicks on this button it executes code with the class below. In this calls there is a Post method that calls a RestAPI. This RestApi requires basic authentication. Any help would be great.
public static class CallRestAPI
{
private static readonly string baseURL = "https://servername/fscmRestApi/resources/11.13.18.05/erpintegrations";
public static async Task<string> Post(string name, string job)
{
var inputData = new Dictionary<string, string>
{
{"name", name },
{"job", job }
};
var input = new FormUrlEncodedContent(inputData);
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage res = await client.PostAsync(baseURL + "users", input))
{
using (HttpContent content = res.Content)
{
string data = await content.ReadAsStringAsync();
if (data != null)
{
return data;
}
}
}
}
return string.Empty;
}
}
You have to add the authorization header:
var byteArray = Encoding.ASCII.GetBytes($"{UserName}:{Password}");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
I did research and didn't find anything related to that. Please, I hope someone can help me.
What do I have?
I have HttpMessaheHandler that is inherited from DelegatingHandler
What do I do?
I'm trying to handle OAuth2 logic inside that HttpMessaheHandler
So I do another request inside HttpMessaheHandler from freshly created HttpClient
What is the problem?
The problem is that HttpResponseMessage is hit 2 times! It happens on line 70
HttpResponseMessage identityResponse = await this._client.SendAsync(requestMessage);
When this line is executed then we are coming back into HttpResponseMessage and starting this logic from the beginning.
What I have already tried?
I have tried to use ASP.NET Core native functionality services.AddHttpClient(...) the same issue.
What do I expect?
I do expect that my freshly created HttpClient does not hit this HttpMessageHandler as it is not bound to this HttpClient
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Common.Core.Abstractions;
using Common.Data;
using Common.Data.Enums;
using Common.Services.Shared;
using Hrimsoft.StringCases;
using Integrations.ECommerce.Storm.Configuration;
using Integrations.ECommerce.Storm.Models;
using Integrations.ECommerce.Storm.Models.Requests;
using Integrations.ECommerce.Storm.Services;
using Microsoft.Extensions.DependencyInjection;
using UrlCombineLib;
namespace Integrations.ECommerce.Storm
{
internal class StormIdentityHttpMessageHandler : DelegatingHandler
{
private readonly RequestOptions _requestOptions;
private readonly IContextProvider _contextProvider;
private readonly IStormIdentityService _stormIdentityService;
private readonly StormSettings _settings;
private readonly IServiceProvider _serviceProvider;
private readonly string _authorizationHeader = "Authorization";
private readonly string _applicationId = "ApplicationId";
private HttpClient _client;
private IJsonSerializer _jsonSerializer;
public StormIdentityHttpMessageHandler(
IContextProvider contextProvider,
IStormIdentityService stormIdentityService,
StormSettings settings,
IServiceProvider serviceProvider)
{
this._contextProvider = contextProvider;
this._stormIdentityService = stormIdentityService;
this._settings = settings;
this._serviceProvider = serviceProvider;
this._requestOptions = new RequestOptions { ContentType = RequestContentType.FormUrlEncoded, PropertyCaseType = PropertyNameCaseType.SnakeCase };
this._client = new HttpClient { BaseAddress = new Uri(this._settings.IdentityServerUrl) };
this._jsonSerializer = serviceProvider.GetRequiredService<IJsonSerializer>();
}
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
string culture = this._contextProvider.GetCulture();
var parameters = new StormOAuth2AuthenticationParameters
{
GrantType = this._settings.GrantType, ClientId = this._settings.ClientId, ClientSecret = this._settings.ClientSecret, Scope = this._settings.Scope
};
HttpRequestMessage requestMessage = this.Post(string.Empty, parameters, SetRequestOptions);
HttpResponseMessage identityResponse = await this._client.SendAsync(requestMessage);
StormAccessToken token = await RetrieveAccessToken(identityResponse);
// // Handle OAuth2. Requesting/Getting the access token.
// IStormIdentityService identityService = this._stormIdentityService;
// string accessToken = await identityService.RequestAccessToken();
//
// // Setting the AccessToken token to the outgoing request
// request.Headers.Add(this._applicationId, this._settings[culture].ApplicationId);
// request.Headers.Add(this._authorizationHeader, $"Bearer {accessToken}");
// HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
//
// if (response.StatusCode == HttpStatusCode.Unauthorized)
// {
// bool forceNewToken = true;
// accessToken = await identityService.RequestAccessToken(forceNewToken);
// request.Headers.Remove(this._authorizationHeader);
// request.Headers.Add(this._authorizationHeader, $"Bearer {accessToken}");
// response = await base.SendAsync(request, cancellationToken);
//
// if (response.StatusCode == HttpStatusCode.Unauthorized)
// {
// throw new ServiceException($"Can't authorize with current token. Token value:\n{accessToken}");
// }
// }
return response;
}
private async Task<StormAccessToken> RetrieveAccessToken(HttpResponseMessage httpResponse)
{
if (httpResponse.Content == null)
{
return default;
}
string content = await httpResponse.Content.ReadAsStringAsync();
if (string.IsNullOrEmpty(content))
{
return default;
}
return JsonSerializer.Deserialize<StormAccessToken>(content);
}
protected virtual async Task<Exception> OnNegativeResponse(HttpResponseMessage response)
{
HttpRequestMessage request = response.RequestMessage;
string details = null;
if (response.Content != null)
{
details = await response.Content.ReadAsStringAsync();
}
string message = $"REST request '{request.Method} - {request.RequestUri}' " +
$"error: {(int)response.StatusCode}, Message: {response.ReasonPhrase}{Environment.NewLine}{details}";
var exception = new Exception(message);
return exception;
}
protected HttpRequestMessage Post(string url = "", object data = null, Action<RequestOptions> setup = null)
=> BuildRequest(HttpMethod.Post, url, data, setup);
protected virtual string BuildResourceUrl(string baseUrl, string resource)
=> UrlCombine.Combine(baseUrl, resource);
private HttpRequestMessage BuildRequest(
HttpMethod method,
string resourceBase,
object body = null,
Action<RequestOptions> setup = null)
{
string fullUrl = BuildResourceUrl(this._client.BaseAddress.ToString(), resourceBase);
var request = new HttpRequestMessage(method, fullUrl);
if (body == null)
{
return request;
}
var options = new RequestOptions();
setup?.Invoke(options);
if (options.ContentType == RequestContentType.FormUrlEncoded)
{
Dictionary<string, string> content = GetFormContent(body, options);
request.Content = new FormUrlEncodedContent(content);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
}
else
{
throw new Exception($"Unsupported content type {options.ContentType}");
}
return request;
}
private Dictionary<string, string> GetFormContent(object data, RequestOptions options)
{
var pairs = data
.GetType()
.GetProperties()
.Select(s => new { Name = ToRequiredCase(s.Name, options.PropertyCaseType), Value = s.GetValue(data, null)?.ToString() })
.Where(s => s.Value != null)
.ToDictionary(k => k.Name, v => v.Value);
return pairs;
string ToRequiredCase(string value, PropertyNameCaseType type)
{
string processedValue = string.Empty;
if (type == PropertyNameCaseType.CamelCase)
{
processedValue = value?.ToCamelCase();
}
else if (type == PropertyNameCaseType.SnakeCase)
{
processedValue = value?.ToSnakeCase();
}
return processedValue;
}
}
private void SetRequestOptions(RequestOptions options)
{
options.ContentType = this._requestOptions.ContentType;
options.PropertyCaseType = this._requestOptions.PropertyCaseType;
}
}
}
I'm trying to create a POST Request for Azure DevOps Teams and Repositories and want to create a new team and a new repository through the API method. My Team is created fine but I don't know how to extend the code to create a repository in the same HttpRequest and also how do I have the 'body' to include both the name of the team and the name of the repository as they both have the same 'name' parameter.
I'm quiet new to C# and Azure functions and don't know how to properly implement this in my own project. I would really appreciate it if someone could guide me into the right direction.
I am using Visual Studio with .NET Core 3.0.
Here is the code so far:
using System.IO;
using System;
using System.Net;
using Microsoft.Azure.WebJobs;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs.Extensions.Http;
namespace TeamsAdd
{
public static class TeamsAdd
{
[FunctionName("Function1")]
public static async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]
HttpRequestMessage req)
{
var personalaccesstoken = "";
var body = new
{
name = "myteamname",
project = new
{
id = "xxxxxxx",
projectname = "myprojectname",
}
};
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", personalaccesstoken))));
//Connecting to the DevOps REST API
var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"https://dev.azure.com/{organization}/_apis/projects/{projectId}/teams?api-version=6.0");
requestMessage.Content = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json");
//Reading Server Response
using (HttpResponseMessage response = await client.SendAsync(requestMessage))
{
if (!response.IsSuccessStatusCode)
{
response.EnsureSuccessStatusCode();
}
return req.CreateResponse(HttpStatusCode.Created, "Teams created successfully!");
}
}
}
}
}
The API used to create a team and repo are different. For more details, please refer to here and here. So we cannot create the two resources in one request. we need to send two requests to create the two different resources.
For example
public static class Function2
{
public static HttpClient Client = new HttpClient();
public static string PAT = "";
[FunctionName("Function2")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
{
Object teamBody = new
{
name = "mytest7878orf",
};
Object repoBody = new
{
name = "mytest85698",
project= new {
id = "8d5fa9a0-1061-4891-977b-f91189a0dcbe",
}
};
var teamRes= sendRequest(HttpMethod.Post, "https://dev.azure.com/{organization}/_apis/projects/{projectId}/teams?api-version=6.0", teamBody);
var repoRes= sendRequest(HttpMethod.Post, "https://dev.azure.com/{organization}/{projectId}/_apis/git/repositories?api-version=6.0", repoBody);
var res = new
{
teamRes = JsonConvert.DeserializeObject(teamRes),
repoRes = JsonConvert.DeserializeObject(repoRes)
};
return req.CreateResponse(HttpStatusCode.OK, JsonConvert.SerializeObject(res), "application/json");
}
public static string sendRequest(HttpMethod method, string url, Object body = null) {
Client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", PAT))));
//Connecting to the DevOps REST API
var requestMessage = new HttpRequestMessage(method, url);
if (body != null) {
requestMessage.Content = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json");
}
using (HttpResponseMessage response = Client.SendAsync(requestMessage).Result)
{
if (!response.IsSuccessStatusCode)
{
try
{
response.EnsureSuccessStatusCode();
}
catch (HttpRequestException ex) {
return ex.Message;
}
}
var content = response.Content.ReadAsStringAsync().Result;
return content;
}
}
}
I'm trying to do a patch http request to change one of the fields in TFS through the TFS REST API. I've tried several approaches, but I always end up with 400 error. Here is what I have right now:
public void SetFieldValue(string value, string path, int id)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(PatchwebAPIUrl("wit/workitems", id.ToString()));
httpWebRequest.ContentType = "application/json-patch+json";
httpWebRequest.Method = "PATCH";
httpWebRequest.Headers["Authorization"] = "Basic" + Base64authorizationToken();
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "[{\"op\":\"replace\"," +
$"\"path\":\"{path}\"," +
$"\"value\":\"{value}\"}}]";
streamWriter.Write(JsonConvert.SerializeObject(json));
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
And the test method that calls this method:
[TestMethod()]
public void setFieldValue()
{
TFSWebAPIImplementation webAPI = new TFSWebAPIImplementation();
webAPI.SetFieldValue("654321", "/fields/Custom.Tracking", 61949);
}
The PatchwebAPIUrl("...") Method is fine, and returns a good URL, when I navigate to it I get the JSON data that I want to edit. I'm not 100% on the path variable but it's used the same as the example provided from Microsoft. The authorization works, just based on the fact that when I mess with it I get a 401 instead.
This is my sample code:
Class for work item:
public class WorkItemAtrr
{
[JsonProperty("id")]
public int id;
[JsonProperty("rev")]
public int rev;
[JsonProperty("fields")]
public Dictionary<string, string> fields;
[JsonProperty("_links")]
public Dictionary<string, Link> _links;
[JsonProperty("relations")]
public List<Relation> relations;
[JsonProperty("url")]
public string url;
}
public class Link
{
[JsonProperty("href")]
public string href;
}
public class Relation
{
[JsonProperty("rel")]
public string rel;
[JsonProperty("url")]
public string url;
[JsonProperty("attributes")]
public RelationAttribute attributes;
}
public class RelationAttribute
{
[JsonProperty("comment")]
public string comment = "";
[JsonProperty("isLocked")]
public bool isLocked;
}
Class for new and updated fields:
public class NewField
{
[JsonProperty("op")]
public string op = "add";
[JsonProperty("path")]
public string path;
[JsonProperty("value")]
public object value;
}
Class for exceptions:
public class RestApiExceptionContainer
{
[JsonProperty("id")]
public int id;
[JsonProperty("innerException")]
public string innerException;
[JsonProperty("message")]
public string message;
[JsonProperty("typeName")]
public string typeName;
[JsonProperty("typeKey")]
public string typeKey;
[JsonProperty("errorCode")]
public int errorCode;
[JsonProperty("evenId")]
public int eventId;
}
Method for update a work item:
private static WorkItemAtrr UpdateWorkItemRest()
{
Dictionary<string, string> _fields = new Dictionary<string, string>();
_fields.Add("REFERENCE_NAME", "VALUE");
var _updatedWi = UpdateWorkItem("ID", _fields).Result;
}
Method for preparing request:
public async Task<WorkItemAtrr> UpdatedWorkItem(int pId, Dictionary<String, String> pFields)
{
//PATCH https://{instance}/DefaultCollection/_apis/wit/workitems/{id}?api-version={version}
string _query_url = String.Format("https://YOUR_SERVER/DefaultCollection/_apis/wit/workitems/{id}?api-version=1.0", pId);
List<Object> flds = new List<Object>();
foreach (var _key in pFields.Keys)
flds.Add(new NewField { op = "add", path = "/fields/" + _key, value = pFields[_key] });
HttpResponseMessage _response = await DoRequest(_query_url, JsonConvert.SerializeObject(flds), ClientMethod.PATCH);
return JsonConvert.DeserializeObject<WorkItemAtrr>(await ProcessResponse(_response));
}
Universal method for request:
private async Task<HttpResponseMessage> DoRequest(string pRequest, string pBody, ClientMethod pClientMethod)
{
try
{
HttpClientHandler _httpclienthndlr = new HttpClientHandler();
//update for your auth
if (UseDefaultCredentials) _httpclienthndlr.Credentials = CredentialCache.DefaultCredentials;
else if (TFSDomain == "") _httpclienthndlr.Credentials = new NetworkCredential(TFSUserName, TFSPassword);
else _httpclienthndlr.Credentials = new NetworkCredential(TFSUserName, TFSPassword, TFSDomain);
using (HttpClient _httpClient = new HttpClient(_httpclienthndlr))
{
switch (pClientMethod)
{
case ClientMethod.GET:
return await _httpClient.GetAsync(pRequest);
case ClientMethod.POST:
return await _httpClient.PostAsync(pRequest, new StringContent(pBody, Encoding.UTF8, "application/json"));
case ClientMethod.PATCH:
var _request = new HttpRequestMessage(new HttpMethod("PATCH"), pRequest);
_request.Content = new StringContent(pBody, Encoding.UTF8, "application/json-patch+json");
return await _httpClient.SendAsync(_request);
default:
return null;
}
}
}
catch (Exception _ex)
{
throw new Exception("Http Request Error", _ex);
}
}
Universal method for response:
public async Task<string> ProcessResponse(HttpResponseMessage pResponse)
{
string _responseStr = "";
if (pResponse != null)
{
if (pResponse.IsSuccessStatusCode)
_responseStr = await pResponse.Content.ReadAsStringAsync();
else
{
_responseStr = await pResponse.Content.ReadAsStringAsync();
var _error = JsonConvert.DeserializeObject<RestApiExceptionContainer>(_responseStr);
throw new RestApiException(_error);
}
}
return _responseStr;
}
A 400 means that the request was malformed. In other words, the data stream sent by the client to the server didn't follow the rules.
In the case of a REST API with a JSON payload, 400's are typically, used to indicate that the JSON is invalid in some way according to the API specification for the service.
So, the issue is caused by the JSON body.
Just try it like below:
string json = "[{\"op\":\"replace\",\"path\":\"/fields/System.Title\",\"value\":\"Title\"}]";
You can also use below sample to update the fields with PATCH method via the REST API, it works for me:
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Newtonsoft.Json;
namespace UpdateWorkItemFiled0411
{
class Program
{
static void Main(string[] args)
{
string password = "xxxx";
string credentials = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "username", password )));
Object[] patchDocument = new Object[1];
patchDocument[0] = new { op = "replace", path = "/relations/attributes/comment", value = "Adding traceability to dependencies" };
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
var patchValue = new StringContent(JsonConvert.SerializeObject(patchDocument), Encoding.UTF8, "application/json-patch+json");
var method = new HttpMethod("PATCH");
var request = new HttpRequestMessage(method, "http://server:8080/tfs/DefaultCollection/_apis/wit/workitems/21?api-version=1.0") { Content = patchValue };
var response = client.SendAsync(request).Result;
if (response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsStringAsync().Result;
}
}
}
}
}
Also you may use nugate package Microsoft.TeamFoundationServer.Client.
Connect to team project from here:
using Microsoft.TeamFoundation.Core.WebApi;
using Microsoft.VisualStudio.Services.Common;
...
//create uri and VssBasicCredential variables
Uri uri = new Uri(url);
VssBasicCredential credentials = new VssBasicCredential("", personalAccessToken);
using (ProjectHttpClient projectHttpClient = new ProjectHttpClient(uri, credentials))
{
IEnumerable<TeamProjectReference> projects = projectHttpClient.GetProjects().Result;
}
my code to add comments:
JsonPatchDocument PatchDocument = new JsonPatchDocument();
PatchDocument.Add(
new JsonPatchOperation()
{
Operation = Operation.Add,
Path = "/fields/System.History",
Value = "Changes from script"
}
);
VssCredentials Cred = new VssCredentials(true);
WorkItemTrackingHttpClient WIClient = new WorkItemTrackingHttpClient(new Uri("http://YOUR_SERVER/tfs/DefaultCollection"), Cred);
WorkItem result = WIClient.UpdateWorkItemAsync(PatchDocument, id).Result;
Okay guys, so unfortunately none of your solutions worked, and I think it's because there was always an extra set of curly brackets on the outside that the TFS API didn't like. Here is my solution that solved my problem:
public void SetFieldValue(string value, string path, int id)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Base64authorizationToken());
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter writer = new JsonTextWriter(sw))
{
writer.Formatting = Formatting.Indented;
writer.WriteStartArray(); // [
writer.WriteStartObject(); // {
writer.WritePropertyName("op"); // "Product:"
writer.WriteValue("replace");
writer.WritePropertyName("path");
writer.WriteValue(path);
writer.WritePropertyName("value");
writer.WriteValue(value);
writer.WriteEndObject(); //}
writer.WriteEnd(); // ]
}
var method = new HttpMethod("PATCH");
var request = new HttpRequestMessage(method, PatchwebAPIUrl("wit/workitems", id.ToString())) { Content = new StringContent(sb.ToString().Trim(new char[] {'{','}'}), Encoding.UTF8, "application/json-patch+json") };
var response = client.SendAsync(request).Result;
if (response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsStringAsync().Result;
}
}
}
I'm trying to write a unit test for polly, but it looks like the return is cached.
Method PostAsyncWithRetry:
using Polly;
using System;
using System.Diagnostics;
using System.Net.Cache;
using System.Net.Http;
public class RetryClient
{
private HttpClient httpClient = new HttpClient(new WebRequestHandler()
{ CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore) });
public HttpResponseMessage PostAsyncWithRetry(
String url,
String path,
StringContent httpContent)
{
httpClient.BaseAddress = new Uri(url);
var retryPolicy =
Policy.Handle<HttpRequestException>()
.OrResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode)
.RetryAsync(3, (exception, retryCount, context) =>
{
Debug.WriteLine("RetryCount: {0}", retryCount);
});
var response = retryPolicy.ExecuteAsync(async () =>
{
return await httpClient.PostAsync(path, httpContent);
}
);
return response.Result;
}
}
Test:
[TestFixture]
class Test
{
private HttpClient mockHTTPClient;
private Mock<WebRequestHandler> mockHttpMessageHandler;
private RetryClient testInstance;
private const String URL = "https://aaa.com";
private const String PATH = "/path";
private const String EXPECTED_STRING_CONTENT = "Some return text";
[SetUp]
public void SetUp()
{
testInstance = new RetryClient();
mockHttpMessageHandler = new Mock<WebRequestHandler>();
mockHttpMessageHandler.Object.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
mockHTTPClient = new HttpClient(mockHttpMessageHandler.Object);
var type = typeof(RetryClient);
var fields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
fields[0].SetValue(testInstance, mockHTTPClient);
}
[Test]
public void TestMEEEE()
{
var responses = new Queue<Task<HttpResponseMessage>>();
responses.Enqueue(Task.FromResult(new HttpResponseMessage
{
StatusCode = HttpStatusCode.NotFound,
Content = new StringContent(EXPECTED_STRING_CONTENT)
}));
responses.Enqueue(Task.FromResult(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(EXPECTED_STRING_CONTENT)
}));
var postContent = new StringContent(EXPECTED_STRING_CONTENT);
mockHttpMessageHandler.Protected()
.Setup<Task>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
.Returns(responses.Dequeue());
var response = testInstance.PostAsyncWithRetry(
URL, PATH, postContent);
mockHttpMessageHandler.Verify();
Assert.AreEqual(responses.Count, 0, "didn't dequeue");
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "Incorrect status code");
}
}
Not sure why, but it looks like the responses queue is only being Dequeue once, this leads me to believe the response is being cache. Does anyone know who is caching the response, and how do I disable it?
Thanks a bunch in advance!
I figured it out. It has nothing to do with caching. During the mock setup, it stores the Dequeue value as a return instead of invoking it every time.
Changing it to () => responses.Dequeue() works now.
Thank you guys!