certChain.ChainStatus and ChainElementStatus is empty or null in custom cert chain validation .net 6 - .net-6.0

we need to do a custom cert chain validation, got the code from one of the forums
but in the call back certChain.ChainStatus and ChainElementStatus are empty or null.
its not validating anything where chain status is there, its just skipping.
Anybody has any pointers on this issue, are we missing anything
var root = new X509Certificate2(#"c:\root.cer");
var inter = new X509Certificate2(#"inter.cer");
var validCertificates = new[] { root, inter };
var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ServerCertificateCustomValidationCallback = (httpRequestMessage, cert, certChain, policyErrors) =>
{
return ValidateCertificate(httpRequestMessage, cert, certChain, policyErrors, validCertificates);
};
var httpClient = new HttpClient(handler);
private bool ValidateCertificate(HttpRequestMessage httpRequestMessage, X509Certificate2 cert,
X509Chain certChain, SslPolicyErrors policyErrors, X509Certificate2[] validCertificates)
{
if (certChain.ChainStatus.Any(status => status.Status != X509ChainStatusFlags.UntrustedRoot))
return false;
foreach (var element in certChain.ChainElements)
{
foreach (var status in element.ChainElementStatus) ---skipping this step and not getting inside
{
if (status.Status == X509ChainStatusFlags.UntrustedRoot)
{
certificates
if (validCertificates.Any(cert => cert.RawData.SequenceEqual(element.Certificate.RawData)))
continue;
}
return false;
}
}
return true;
}

Those arrays are empty when the element (or overall chain, depending on which one) have no errors.
You're showing a state that is appropriate to a trusted chain.

Related

ListBlobsSegmentedAsync keeps returning the same continuation token

My app uses ListBlobsSegmentedAsync and the following loop never finishes:
// List blobs existing in container
HashSet<string> existingBlobNames = new HashSet<string>();
BlobResultSegment segment;
do
{
segment = await container.ListBlobsSegmentedAsync(null, cancellationToken).ConfigureAwait(false);
foreach (IListBlobItem blobListItem in segment.Results)
{
CloudBlockBlob blob = blobListItem as CloudBlockBlob;
if (blob != null)
{
existingBlobNames.Add(blob.Name);
}
}
}
while (segment.ContinuationToken != null);
It always returns exactly the same ContinuationToken & no results.
This was me who ported this logic from another service which worked successfully for years. Turned out that service always had the same bug. But since there could have been at most 10 blobs in a container it never hit it.
This code needs actually to pass a continuation token =) Here is the corrected version.
BlobContinuationToken continuationToken = null;
do
{
BlobResultSegment segment = await container.ListBlobsSegmentedAsync(continuationToken, cancellationToken).ConfigureAwait(false);
foreach (IListBlobItem blobListItem in segment.Results)
{
CloudBlockBlob blob = blobListItem as CloudBlockBlob;
if (blob != null)
{
existingBlobNames.Add(blob.Name);
}
}
continuationToken = segment.ContinuationToken;
}
while (continuationToken != null);

Google API Client for .NET: How to implement Exponential Backoff

I've created a method to add members in a Batch Request to a google group using .NET core and google's .NET client library. The code looks like this:
private void InitializeGSuiteDirectoryService()
{
_directoryServiceCredential = GoogleCredential
.FromJson(GlobalSettings.Instance.GSuiteSettings.Credentials)
.CreateScoped(_scopes)
.CreateWithUser(GlobalSettings.Instance.GSuiteSettings.User);
_directoryService = new DirectoryService(new BaseClientService.Initializer()
{
HttpClientInitializer = _directoryServiceCredential,
ApplicationName = _applicationName
});
}
public OperationResult<int> AddGroupMembers(Group group, IEnumerable<Member> members)
{
var result = new OperationResult<int>();
var memberList = members.ToList();
var batchRequestCount = 0;
if (memberList.Any())
{
var request = new BatchRequest(_directoryService);
foreach (var member in memberList)
{
batchRequestCount++;
request.Queue<Members>(_directoryService.Members.Insert(member, group.Id), (content, error, i, message) =>
{
if (message.IsSuccessStatusCode)
{
//log OK
}
else
{
// Implement Exponential backoff only on the request that failed.
}
});
if (batchRequestCount == 30|| member.Equals(memberList.Last()))
{
request.ExecuteAsync().Wait();
request = new BatchRequest(_directoryService); //Clear queue
}
}
}
return result;
}
The logic works fine if the amount of members is small; however, when the members count is let's say 100( this is the max amount of users in my google's test instance), I get an Error from Google that reads: "quotaExceeded". According to Google's documentation, the limit for a batch request on their Admin SDK is 1000 and I've set my logic to Execute when we reach a limit of 30.
The QUESTION is: How do I implement error handling to retry whenever I get this error? Their documentation suggests implementing 'Exponential Backoff' with a response that contains a 'retry-able error'(I don't see this when I inspect my response).
So here's what I ended up doing to implement Exponential Backoff on my call to add members to a Gsuite group. Since I'm using dotnet core, I was able to use 'Polly', which is a resilience and transient-fault-handling library that offers this functionality out of the box. There may be some need for refactoring, but here's what the code looks like for now:
public OperationResult<int> AddGroupMembers(Group group, IEnumerable<Member> members)
{
var result = new OperationResult<int>();
var memberList = members.ToList();
var batchRequestCount = 0;
if (memberList.Any())
{
var request = new BatchRequest(_directoryService);
foreach (var member in memberList)
{
retryRequest = false; // This variable needs to be declared at the class level to guarantee the value is available to the original thread running the process.
batchRequestCount++;
request.Queue<Members>(_directoryService.Members.Insert(member, group.Id), (content, error, i, message) =>
{
// If error code is 'quotaExceeded' retry the request ( You can add as many error codes as you'd like to retry here)
if (error.Code == 403)
{
retryRequest = true;
}
});
// Execute batch request to add members in batches of 30 member max
if (batchRequestCount == 30|| member.Equals(memberList.Last()))
{
// Below is what the code to retry using polly looks like
var response = Policy
.HandleResult<HttpResponseMessage>(message => message.StatusCode == HttpStatusCode.Conflict)
.WaitAndRetry(new[]
{
TimeSpan.FromSeconds(1),
TimeSpan.FromSeconds(2),
TimeSpan.FromSeconds(4)
}, (results, timeSpan, retryCount, context) =>
{
// Log Warn saying a retry was required.
})
.Execute(() =>
{
var httpResponseMsg = new HttpResponseMessage();
// Execute batch request Synchronously
request.ExecuteAsync().Wait();
if (retryRequest)
{
httpResponseMsg.StatusCode = HttpStatusCode.Conflict;
retryRequest = false;
}
else
{
httpResponseMsg.StatusCode = HttpStatusCode.OK;
}
return httpResponseMsg;
});
if (response.IsSuccessStatusCode)
{
// Log info
}
else
{
// Log warn
}
requestCount = 0;
request = new BatchRequest(_directoryService);
batchCompletedCount++;
}
}
}
return result;
}

Can't advertise on bluetooth

I want to create a Gatt Server in my Xamarin.Forms app so that other devices can scan for it via bluetooth. I am using this plugin:
https://github.com/aritchie/bluetoothle
This is my code to create a Gatt Server and advertise data:
server = CrossBleAdapter.Current.CreateGattServer();
var service = server.AddService(serviceGuid, true);
var characteristic = service.AddCharacteristic(
characteristicGuid,
CharacteristicProperties.Read |
CharacteristicProperties.Write | CharacteristicProperties.WriteNoResponse,
GattPermissions.Read | GattPermissions.Write
);
var notifyCharacteristic = service.AddCharacteristic
(
notifyCharacteristicGuid,
CharacteristicProperties.Indicate | CharacteristicProperties.Notify,
GattPermissions.Read | GattPermissions.Write
);
IDisposable notifyBroadcast = null;
notifyCharacteristic.WhenDeviceSubscriptionChanged().Subscribe(e =>
{
var #event = e.IsSubscribed ? "Subscribed" : "Unsubcribed";
if (notifyBroadcast == null)
{
notifyBroadcast = Observable
.Interval(TimeSpan.FromSeconds(1))
.Where(x => notifyCharacteristic.SubscribedDevices.Count > 0)
.Subscribe(_ =>
{
Debug.WriteLine("Sending Broadcast");
var dt = DateTime.Now.ToString("g");
var bytes = Encoding.UTF8.GetBytes("SendingBroadcast");
notifyCharacteristic.Broadcast(bytes);
});
}
});
characteristic.WhenReadReceived().Subscribe(x =>
{
var write = "HELLO";
// you must set a reply value
x.Value = Encoding.UTF8.GetBytes(write);
x.Status = GattStatus.Success; // you can optionally set a status, but it defaults to Success
});
characteristic.WhenWriteReceived().Subscribe(x =>
{
var write = Encoding.UTF8.GetString(x.Value, 0, x.Value.Length);
Debug.WriteLine("in WhenWriteReceived() value: " + write);
// do something value
});
await server.Start(new AdvertisementData
{
LocalName = "DariusServer",
ServiceUuids = new List<Guid>() { serverServiceGuid }
});
I am using this app to scan for my advertisement data:
https://play.google.com/store/apps/details?id=no.nordicsemi.android.mcp
I can't discover my app with it. I don't know what I'm doing wrong? I am testing with a real device, SM-T350 tablet
I spent countless hours to get this plugin to work with no luck. But this native code works for anyone else who has the same problem:
private async Task AndroidBluetooth()
{
try
{
await Task.Delay(5000); // just to make sure bluetooth is ready to go, this probably isn't needed, but good for peace of mind during testing
BluetoothLeAdvertiser advertiser = BluetoothAdapter.DefaultAdapter.BluetoothLeAdvertiser;
var advertiseBuilder = new AdvertiseSettings.Builder();
var parameters = advertiseBuilder.SetConnectable(true)
.SetAdvertiseMode(AdvertiseMode.Balanced)
//.SetTimeout(10000)
.SetTxPowerLevel(AdvertiseTx.PowerHigh)
.Build();
AdvertiseData data = (new AdvertiseData.Builder()).AddServiceUuid(new ParcelUuid(Java.Util.UUID.FromString("your UUID here"))).Build();
MyAdvertiseCallback callback = new MyAdvertiseCallback();
advertiser.StartAdvertising(parameters, data, callback);
}
catch(Exception e)
{
}
}
public class MyAdvertiseCallback : AdvertiseCallback
{
public override void OnStartFailure([GeneratedEnum] AdvertiseFailure errorCode)
{
// put a break point here, in case something goes wrong, you can see why
base.OnStartFailure(errorCode);
}
public override void OnStartSuccess(AdvertiseSettings settingsInEffect)
{
base.OnStartSuccess(settingsInEffect);
}
}
}
Just to note, it wouldn't work if if I included the device name, because the bluetooth transmission would be too large in that case with a service UUID (max 31 bytes I believe).

How to retrieve all contacts from Microsoft Exchange using EWS Managed API?

all I need to do is to retrieve all contacts from Microsoft Exchange. I did some research and the best possible option for me should be to use EWS Managed API. I am using Visual Studio and C# programming leanguage.
I think I am able to connect to Office365 account, because I am able to send a message in a program to specific email. But I am not able to retrieve the contacts.
If I create a contact directly in source code, the contact will be created in Office365->People aplication. But I don't know why! I thought I was working with Exchange aplication.
Summarize:
Is there any possibility how to get all contacts from Office365->Admin->Exchange->Acceptencers->Contacts ?
Here is my code:
class Program
{
static void Main(string[] args)
{
// connecting to my Exchange account
ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.Credentials = new WebCredentials("office365email#test.com", "password123");
/*
// debugging
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
*/
service.AutodiscoverUrl("office365email#test.com", RedirectionUrlValidationCallback);
// send a message works good
EmailMessage email = new EmailMessage(service);
email.ToRecipients.Add("matoskok1#gmail.com");
email.Subject = "HelloWorld";
email.Body = new MessageBody("Toto je testovaci mail");
email.Send();
// Create the contact creates a contact in Office365 -> People application..Don't know why there and not in Office365 -> Exchange
/*Contact contact = new Contact(service);
// Specify the name and how the contact should be filed.
contact.GivenName = "Brian";
contact.MiddleName = "David";
contact.Surname = "Johnson";
contact.FileAsMapping = FileAsMapping.SurnameCommaGivenName;
// Specify the company name.
contact.CompanyName = "Contoso";
// Specify the business, home, and car phone numbers.
contact.PhoneNumbers[PhoneNumberKey.BusinessPhone] = "425-555-0110";
contact.PhoneNumbers[PhoneNumberKey.HomePhone] = "425-555-0120";
contact.PhoneNumbers[PhoneNumberKey.CarPhone] = "425-555-0130";
// Specify two email addresses.
contact.EmailAddresses[EmailAddressKey.EmailAddress1] = new EmailAddress("brian_1#contoso.com");
contact.EmailAddresses[EmailAddressKey.EmailAddress2] = new EmailAddress("brian_2#contoso.com");
// Specify two IM addresses.
contact.ImAddresses[ImAddressKey.ImAddress1] = "brianIM1#contoso.com";
contact.ImAddresses[ImAddressKey.ImAddress2] = " brianIM2#contoso.com";
// Specify the home address.
PhysicalAddressEntry paEntry1 = new PhysicalAddressEntry();
paEntry1.Street = "123 Main Street";
paEntry1.City = "Seattle";
paEntry1.State = "WA";
paEntry1.PostalCode = "11111";
paEntry1.CountryOrRegion = "United States";
contact.PhysicalAddresses[PhysicalAddressKey.Home] = paEntry1;
// Specify the business address.
PhysicalAddressEntry paEntry2 = new PhysicalAddressEntry();
paEntry2.Street = "456 Corp Avenue";
paEntry2.City = "Seattle";
paEntry2.State = "WA";
paEntry2.PostalCode = "11111";
paEntry2.CountryOrRegion = "United States";
contact.PhysicalAddresses[PhysicalAddressKey.Business] = paEntry2;
// Save the contact.
contact.Save();
*/
// msdn.microsoft.com/en-us/library/office/jj220498(v=exchg.80).aspx
// Get the number of items in the Contacts folder.
ContactsFolder contactsfolder = ContactsFolder.Bind(service, WellKnownFolderName.Contacts);
Console.WriteLine(contactsfolder.TotalCount);
// Set the number of items to the number of items in the Contacts folder or 50, whichever is smaller.
int numItems = contactsfolder.TotalCount < 50 ? contactsfolder.TotalCount : 50;
// Instantiate the item view with the number of items to retrieve from the Contacts folder.
ItemView view = new ItemView(numItems);
// To keep the request smaller, request only the display name property.
view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ContactSchema.DisplayName);
// Retrieve the items in the Contacts folder that have the properties that you selected.
FindItemsResults<Item> contactItems = service.FindItems(WellKnownFolderName.Contacts, view);
// Display the list of contacts.
foreach (Item item in contactItems)
{
if (item is Contact)
{
Contact contact1 = item as Contact;
Console.WriteLine(contact1.DisplayName);
}
}
Console.ReadLine();
} // end of Main() method
/*===========================================================================================================*/
private static bool CertificateValidationCallBack(
object sender,
System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
// If the certificate is a valid, signed certificate, return true.
if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
{
return true;
}
// If there are errors in the certificate chain, look at each error to determine the cause.
if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
{
if (chain != null && chain.ChainStatus != null)
{
foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
{
if ((certificate.Subject == certificate.Issuer) &&
(status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot))
{
// Self-signed certificates with an untrusted root are valid.
continue;
}
else
{
if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
{
// If there are any other errors in the certificate chain, the certificate is invalid,
// so the method returns false.
return false;
}
}
}
}
// When processing reaches this line, the only errors in the certificate chain are
// untrusted root errors for self-signed certificates. These certificates are valid
// for default Exchange server installations, so return true.
return true;
}
else
{
// In all other cases, return false.
return false;
}
}
private static bool RedirectionUrlValidationCallback(string redirectionUrl)
{
// The default for the validation callback is to reject the URL.
bool result = false;
Uri redirectionUri = new Uri(redirectionUrl);
// Validate the contents of the redirection URL. In this simple validation
// callback, the redirection URL is considered valid if it is using HTTPS
// to encrypt the authentication credentials.
if (redirectionUri.Scheme == "https")
{
result = true;
}
return result;
}
}
seems like you are already doing a good job doing a FindItems() method.
In order to get all contacts all you need to add is a SearchFilter, in this case I'd recommend doing the Exists() filter as you can simply say Find All contacts with an id.
See my example below if you need an example of a Full Windows Application dealing with contacts see my github page github.com/rojobo
Dim oFilter As New SearchFilter.Exists(ItemSchema.Id)
Dim oResults As FindItemsResults(Of Item) = Nothing
Dim oContact As Contact
Dim blnMoreAvailable As Boolean = True
Dim intSearchOffset As Integer = 0
Dim oView As New ItemView(conMaxChangesReturned, intSearchOffset, OffsetBasePoint.Beginning)
oView.PropertySet = BasePropertySet.IdOnly
Do While blnMoreAvailable
oResults = pService.FindItems(WellKnownFolderName.Contacts, oFilter, oView)
blnMoreAvailable = oResults.MoreAvailable
If Not IsNothing(oResults) AndAlso oResults.Items.Count > 0 Then
For Each oExchangeItem As Item In oResults.Items
Dim oExchangeContactId As ItemId = oExchangeItem.Id
//do something else
Next
If blnMoreAvailable Then oView.Offset = oView.Offset + conMaxChangesReturned
End If
Loop
How to retrieve all contacts from Microsoft Exchange using EWS Managed API?
If your question is how to retrieve the Exchange Contacts using EWS, you're already done with it.
Office365->People is just the right app to manipulate your Exchange contacts. If you check out the People app URL, it's something similar to https://outlook.office365.com/owa/?realm=xxxxxx#exsvurl=1&ll-cc=1033&modurl=2, owa is the synonym for outlook web app.

How can I check for a response cookie in Asp.net Core MVC (aka Asp.Net 5 RC1)?

I'm converting a web forms application to asp.net core mvc. In my web forms application sometimes after I set some response cookies other code needs to see if they were set, and if so, access the cookie's properties (i.e. value, Expires, Secure, http). In webforms and MVC 5 it's possible to iterate over the cookies and return any particular cookies like so (old school I know)
for(int i = 0; i < cookies.Count; i++) {
if(cookies[i].Name == cookieName) {
return cookies[i];
}
}
But the interface for accessing response cookies in asp.net core mvc looks like this:
Based on this interface I don't see a way to check to see if a response cookie exists and obtain it's properties. But there has gotta be some way to do it?
In an action method I tried setting two cookies on the response object and then immediately trying to access them. But intellisense doesn't show any methods, properties or indexers that would allow me to access them:
For a moment, I thought that perhaps I could use Response.Cookies.ToString(); and just parse the information to find my cookie info, but alas, the ToString() call returns "Microsoft.AspNet.Http.Internal.ResponseCookies" because the object doesn't override the default implementation.
Just for fun I also checked the current dev branch of GitHub to see if the interface has changed since RC1 but it has not. So given this interface, how do I check for the existence of a response cookie and get it's properties? I've thought about trying to hack in via the response headers collection but that seems pretty lame.
There is an extension method available in Microsoft.AspNetCore.Http.Extensions called GetTypedHeaders(). This can be called on HttpContext.Response to read Set-Cookie headers. For example in middleware perhaps we want to intercept a Set-Cookie response header and replace it:
public async Task Invoke(HttpContext httpContext)
{
httpContext.Response.OnStarting(state =>
{
var context = (HttpContext)state;
var setCookieHeaders = context.Response.GetTypedHeaders().SetCookie;
// We assume only one cookie is found. You could loop over multiple matches instead.
// setCookieHeaders may be null if response doesn't contain set-cookie headers
var cookie = setCookieHeaders?.FirstOrDefault(x => x.Name == "mycookiename");
if (cookie == null)
{
return Task.CompletedTask;
}
var opts = new CookieOptions
{
HttpOnly = true,
Expires = DateTimeOffset.Now.AddHours(12),
SameSite = SameSiteMode.Lax,
Secure = true
};
context.Response.Cookies.Delete(cookie.Name.Value);
context.Response.Cookies.Append(cookie.Name.Value, "mynewcookievalue", opts);
return Task.CompletedTask;
}, httpContext);
await _next(httpContext);
}
Here's how I get the value of a cookie from a Response. Something like this could be used to get the whole cookie if required:
string GetCookieValueFromResponse(HttpResponse response, string cookieName)
{
foreach (var headers in response.Headers.Values)
foreach (var header in headers)
if (header.StartsWith($"{cookieName}="))
{
var p1 = header.IndexOf('=');
var p2 = header.IndexOf(';');
return header.Substring(p1 + 1, p2 - p1 - 1);
}
return null;
}
There is an obvious problem with Shaun's answer: it will match any HTTP-header having matching value. The idea should be to match only cookies.
A minor change like this should do the trick:
string GetCookieValueFromResponse(HttpResponse response, string cookieName)
{
foreach (var headers in response.Headers)
{
if (headers.Key != "Set-Cookie")
continue;
string header = headers.Value;
if (header.StartsWith($"{cookieName}="))
{
var p1 = header.IndexOf('=');
var p2 = header.IndexOf(';');
return header.Substring(p1 + 1, p2 - p1 - 1);
}
}
return null;
}
Now the checking for a cookie name will target only actual cookie-headers.
You can use this function to get full information about the cookie set value
private SetCookieHeaderValue GetCookieValueFromResponse(HttpResponse response, string cookieName)
{
var cookieSetHeader = response.GetTypedHeaders().SetCookie;
if (cookieSetHeader != null)
{
var setCookie = cookieSetHeader.FirstOrDefault(x => x.Name == cookieName);
return setCookie;
}
return null;
}
In my case I had to get only value of auth= and don't care about other values, but you can easy rewrite code to get dict of cookie values.
I wrote this extension for HttpResponseMessage, in order to avoid work with index and substring, I separate string to array and then cast it to dictionary
internal static string GetCookieValueFromResponse(this HttpResponseMessage httpResponse, string cookieName)
{
foreach (var cookieStr in httpResponse.Headers.GetValues("Set-Cookie"))
{
if(string.IsNullOrEmpty(cookieStr))
continue;
var array = cookieStr.Split(';')
.Where(x => x.Contains('=')).Select(x => x.Trim());
var dict = array.Select(item => item.Split(new[] {'='}, 2)).ToDictionary(s => s[0], s => s[1]);
if (dict.ContainsKey(cookieName))
return dict[cookieName];
}
return null;
}
You can get the cookie string value from the response using this method. In this case, I'm using this logic in a CookieService, that is the reason you will see that I'm using the _contextAccessor. Notice that in this case, I'm returning null if the value of the cookie is empty. (This is optional)
private string GetCookieFromResponse(string cookieName)
{
var cookieSetHeader = _contextAccessor.HttpContext.Response.GetTypedHeaders().SetCookie;
var cookie = cookieSetHeader?.FirstOrDefault(x => x.Name == cookieName && !string.IsNullOrEmpty(x.Value.ToString()));
var cookieValue = cookie?.Value.ToString();
if (!string.IsNullOrEmpty(cookieValue))
{
cookieValue = Uri.UnescapeDataString(cookieValue);
}
return cookieValue;
}
If you are looking for a solution that gets the cookie from the response or the request in that order then you can use this.
private string GetCookieString(string cookieName)
{
return GetCartCookieFromResponse(cookieName) ?? GetCartCookieFromRequest(cookieName) ?? "";
}
private string GetCookieFromRequest(string cookieName)
{
return _contextAccessor.HttpContext.Request.Cookies.ContainsKey(cookieName) ? _contextAccessor.HttpContext.Request.Cookies[cookieName] : null;
}
private string GetCookieFromResponse(string cookieName)
{
var cookieSetHeader = _contextAccessor.HttpContext.Response.GetTypedHeaders().SetCookie;
var cookie = cookieSetHeader?.FirstOrDefault(x => x.Name == cookieName && !string.IsNullOrEmpty(x.Value.ToString()));
var cookieValue = cookie?.Value.ToString();
if (!string.IsNullOrEmpty(cookieValue))
{
cookieValue = Uri.UnescapeDataString(cookieValue);
}
return cookieValue;
}
The snippet seems to work for me. The result for me (derived from Shaun and Ron) looks like:
public static string GetCookieValueFromResponse(HttpResponse response, string cookieName)
{
// inspect the cookies in HttpResponse.
string match = $"{cookieName}=";
var p1 = match.Length;
foreach (var headers in response.Headers)
{
if (headers.Key != "Set-Cookie")
continue;
foreach (string header in headers.Value)
{
if (header.StartsWith(match) && header.Length > p1 && header[p1] != ';')
{
var p2 = header.IndexOf(';', p1);
return header.Substring(p1 + 1, p2 - p1 - 1);
}
}
}
return null;
}
In cases where multiple "Set-Cookie" headers exists the last one should be used:
private string GetCookieValueFromResponse(Microsoft.AspNetCore.Http.HttpResponse response, string cookieName)
{
var value = string.Empty;
foreach (var header in response.Headers["Set-Cookie"])
{
if (!header.Trim().StartsWith($"{cookieName}="))
continue;
var p1 = header.IndexOf('=');
var p2 = header.IndexOf(';');
value = header.Substring(p1 + 1, p2 - p1 - 1);
}
return value;
}

Resources