public async Task <FilterDownloadResult> GetAsync(FilterDownloadResult filter) { var file = new FileInfo(filterPath); if (!file.Exists) { return(null); } // Find the Etag var etagFile = new FileInfo(file.FullName + ".etag"); if (!etagFile.Exists) { return(null); } var result = new FilterDownloadResult { FilterTimestamp = file.LastWriteTimeUtc, Etag = EntityTagHeaderValue.Parse(File.ReadAllText(etagFile.FullName)), Stream = new MemoryStream((int)file.Length) }; using (var stream = file.OpenRead()) { await stream.CopyToAsync(result.Stream); } result.Length = result.Stream.Length; return(result); }
public void Parse() { var res = EntityTagHeaderValue.Parse("\"c\""); Assert.AreEqual("\"c\"", res.Tag, "#1"); Assert.IsFalse(res.IsWeak, "#2"); }
/// <summary> /// /// </summary> /// <param name="actionExecutedContext"></param> public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { if (actionExecutedContext.Response != null && actionExecutedContext.Response.IsSuccessStatusCode) { var cacheData = new CachedData { Etag = $"\"{Guid.NewGuid().ToString()}\"", CreateAt = DateTime.Now }; if (Location != ApiCacheLocation.Client && Location != ApiCacheLocation.Downstream) { cacheData.ContentData = actionExecutedContext.Response.Content.ReadAsByteArrayAsync().Result; cacheData.MediaType = actionExecutedContext.Response.Content.Headers.ContentType.MediaType; string key; if (!TryGetCacheKeyFromProperties(actionExecutedContext.Request, out key)) { key = GetCacheKey(actionExecutedContext.ActionContext); } Provider.Set(key, cacheData, cacheData.CreateAt.AddSeconds(Duration)); } if (Location != ApiCacheLocation.Server) { SetCacheHeader(actionExecutedContext.Response, cacheData.CreateAt.AddSeconds(Duration)); actionExecutedContext.Response.Headers.ETag = EntityTagHeaderValue.Parse(cacheData.Etag); } } }
private void CheckInvalidParse(string input) { Assert.Throws <FormatException>(() => { EntityTagHeaderValue.Parse(input); }); Assert.False(EntityTagHeaderValue.TryParse(input, out EntityTagHeaderValue result)); Assert.Null(result); }
/// <summary> /// Applies the condition in case it is not null to the Http request. /// </summary> /// <param name="accessCondition">Access condition to be added to the request.</param> /// <param name="requestHeaders">The request headers to be modified.</param> public static void ApplyAccessCondition(this AccessCondition accessCondition, HttpRequestHeaders requestHeaders) { if (accessCondition != null) { if (!string.IsNullOrEmpty(accessCondition.IfMatchETag)) { if (accessCondition.IfMatchETag.Equals(AccessCondition.ETagWildcard, StringComparison.OrdinalIgnoreCase)) { requestHeaders.IfMatch.Add(EntityTagHeaderValue.Any); } else { requestHeaders.IfMatch.Add(EntityTagHeaderValue.Parse(accessCondition.IfMatchETag)); } } if (!string.IsNullOrEmpty(accessCondition.IfNoneMatchETag)) { if (accessCondition.IfNoneMatchETag.Equals(AccessCondition.ETagWildcard, StringComparison.OrdinalIgnoreCase)) { requestHeaders.IfNoneMatch.Add(EntityTagHeaderValue.Any); } else { requestHeaders.IfNoneMatch.Add(EntityTagHeaderValue.Parse(accessCondition.IfNoneMatchETag)); } } requestHeaders.IfModifiedSince = accessCondition.IfModifiedSinceTime; requestHeaders.IfUnmodifiedSince = accessCondition.IfNotModifiedSinceTime; } }
/// <summary> /// Applies the condition to the web request. /// </summary> /// <param name="request">The request to be modified.</param> /// <param name="accessCondition">Access condition to be added to the request.</param> internal static void ApplyAccessCondition(this StorageRequestMessage request, AccessCondition accessCondition) { if (accessCondition != null) { if (!string.IsNullOrEmpty(accessCondition.IfMatchETag)) { request.Headers.IfMatch.Add(EntityTagHeaderValue.Parse(accessCondition.IfMatchETag)); } if (!string.IsNullOrEmpty(accessCondition.IfNoneMatchETag)) { if (accessCondition.IfNoneMatchETag.Equals(EntityTagHeaderValue.Any.ToString(), StringComparison.OrdinalIgnoreCase)) { request.Headers.IfNoneMatch.Add(EntityTagHeaderValue.Any); } else { request.Headers.IfNoneMatch.Add(EntityTagHeaderValue.Parse(accessCondition.IfNoneMatchETag)); } } request.Headers.IfModifiedSince = accessCondition.IfModifiedSinceTime; request.Headers.IfUnmodifiedSince = accessCondition.IfNotModifiedSinceTime; request.ApplyLeaseId(accessCondition); } }
public async Task Delete_Returns_PreconditionFailed_WithOriginalValue_IfVersionMismatch() { TestEntity entity = CreateTestEntity(); Uri location; // Post a new entity and verify entity returned using (HttpResponseMessage postResponse = await this.testClient.PostAsJsonAsync(Address, entity)) { Assert.Equal(HttpStatusCode.Created, postResponse.StatusCode); location = postResponse.Headers.Location; } // Try to delete the entity with wrong version HttpRequestMessage deleteRequest = new HttpRequestMessage(HttpMethod.Delete, location); deleteRequest.Headers.IfMatch.Add(EntityTagHeaderValue.Parse("\"QUJDREVG\"")); using (HttpResponseMessage deleteResponse = await this.testClient.SendAsync(deleteRequest)) { TestEntity conflict = await deleteResponse.Content.ReadAsAsync <TestEntity>(); Assert.Equal(HttpStatusCode.PreconditionFailed, deleteResponse.StatusCode); Assert.NotNull(conflict.CreatedAt); Assert.NotNull(conflict.UpdatedAt); } // Query the entity back to ensure it was *not* deleted using (HttpResponseMessage queryResponse = await this.testClient.GetAsync(location)) { Assert.Equal(HttpStatusCode.OK, queryResponse.StatusCode); } }
/// <inheritdoc /> public EntityTagHeaderValue Generate(string requestUrl, string responseBody) { string fingerprint = _fingerprintGenerator.Generate(ArrayFactory.Create(requestUrl, responseBody)); string eTagValue = "\"" + fingerprint + "\""; return(EntityTagHeaderValue.Parse(eTagValue)); }
public async Task DeleteAsync_Throws_Conflict_IfVersionMismatch() { // Arrange Collection <Movie> movies = new Collection <Movie>(); foreach (Movie movie in TestData.Movies) { Movie insertedMovie = await this.manager.InsertAsync(movie); movies.Add(insertedMovie); } this.request.Headers.IfMatch.Add(EntityTagHeaderValue.Parse("\"QUJDREVG\"")); foreach (Movie movie in movies) { this.context = new MovieModelContext(); MappedEntityDomainManagerMock deleteDomainManager = new MappedEntityDomainManagerMock(this); HttpResponseException ex = await AssertEx.ThrowsAsync <HttpResponseException>(async() => await deleteDomainManager.DeleteAsync(movie.Id)); Movie conflict; ex.Response.TryGetContentValue <Movie>(out conflict); Assert.Equal(HttpStatusCode.PreconditionFailed, ex.Response.StatusCode); Assert.Equal(movie.Version, conflict.Version); } }
public static IDictionary <string, object> IfMatch(HttpRequest request, Type elementType) { StringValues ifMatchValues; if (request.Headers.TryGetValue("If-Match", out ifMatchValues)) { var etagHeaderValue = EntityTagHeaderValue.Parse(ifMatchValues.SingleOrDefault()); if (etagHeaderValue != null) { var values = request .GetRequestContainer() .GetRequiredService <IETagHandler>() .ParseETag(etagHeaderValue) ?? new Dictionary <string, object>(); return(elementType .GetProperties() .Where(pi => pi.GetCustomAttributes(typeof(ConcurrencyCheckAttribute), false).Any()) .OrderBy(pi => pi.Name) .Select((pi, i) => new { Index = i, Name = pi.Name }) .ToDictionary(p => p.Name, p => values[p.Index.ToString()])); } } return(null); }
private IReadOnlyDictionary <string, object> GetOriginalValues(IEdmEntitySet entitySet) { var originalValues = new Dictionary <string, object>(); if (Request.Headers.TryGetValue("IfMatch", out var ifMatchValues)) { var etagHeaderValue = EntityTagHeaderValue.Parse(ifMatchValues.SingleOrDefault()); var etag = Request.GetETag(etagHeaderValue); etag.ApplyTo(originalValues); originalValues.Add(IfMatchKey, etagHeaderValue.Tag); return(originalValues); } if (Request.Headers.TryGetValue("IfNoneMatch", out var ifNoneMatchValues)) { var etagHeaderValue = EntityTagHeaderValue.Parse(ifNoneMatchValues.SingleOrDefault()); var etag = Request.GetETag(etagHeaderValue); etag.ApplyTo(originalValues); originalValues.Add(IfNoneMatchKey, etagHeaderValue.Tag); return(originalValues); } // return 428(Precondition Required) if entity requires concurrency check. var model = api.GetModel(); var needEtag = model.IsConcurrencyCheckEnabled(entitySet); if (needEtag) { return(null); } return(originalValues); }
public Task <HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { var content = new PushStreamContent(async(strm, _, __) => { using (strm) { await _blob.DownloadToStreamAsync(strm); } }); content.Headers.ContentType = MediaTypeHeaderValue.Parse(_blob.Properties.ContentType); if (!String.IsNullOrEmpty(_blob.Properties.ContentEncoding)) { content.Headers.ContentEncoding.Add(_blob.Properties.ContentEncoding); } if (!String.IsNullOrEmpty(_blob.Properties.ContentLanguage)) { content.Headers.ContentLanguage.Add(_blob.Properties.ContentLanguage); } var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = content }; if (!String.IsNullOrEmpty(_blob.Properties.ETag)) { response.Headers.ETag = EntityTagHeaderValue.Parse(_blob.Properties.ETag); } return(Task.FromResult(response)); }
public HttpResponseMessage Download() { try { // Ensure JSON cache file exists var physicalPath = HostingEnvironment.MapPath(Constants.JsonCachePath); if (!File.Exists(physicalPath)) { Refresh(); } // Check if the JSON cache has been updated since the last request from the client var md5Hash = File.ReadAllText(HostingEnvironment.MapPath(Constants.JsonCacheMd5Path)); var responseETag = EntityTagHeaderValue.Parse($"\"{md5Hash}\""); var requestETag = Request.Headers.IfNoneMatch.FirstOrDefault(); if (requestETag != null && requestETag.Tag == responseETag.Tag) { return(Request.CreateResponse(HttpStatusCode.NotModified)); } // Create and return JSON response from file var stream = new FileStream(physicalPath, FileMode.Open); var response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new StreamContent(stream); response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); response.Headers.ETag = responseETag; return(response); } catch (Exception exception) { Logger.Error <JsonCacheController>("Could not serve JSON cache.", exception); return(Request.CreateResponse(HttpStatusCode.InternalServerError)); } }
protected void SetETagHeader <T>(HttpResponseMessage response, T resource) where T : Resource { if (!string.IsNullOrWhiteSpace(resource.Meta.Version) && ServerConfiguration.IsFeatureSupported(ScimFeatureType.ETag)) { response.Headers.ETag = EntityTagHeaderValue.Parse(resource.Meta.Version); } }
private void CheckValidParse(string input, EntityTagHeaderValue expectedResult) { EntityTagHeaderValue result = EntityTagHeaderValue.Parse(input); Assert.Equal(expectedResult, result); Assert.True(EntityTagHeaderValue.TryParse(input, out result)); Assert.Equal(expectedResult, result); }
/* ----------------------------------------------------------------- */ /// /// SetEntityTag /// /// <summary> /// リクエストヘッダに EntityTag を設定します。 /// </summary> /// /* ----------------------------------------------------------------- */ private void SetEntityTag(HttpRequestHeaders headers) => this.LogWarn(() => { if (!UseEntityTag || string.IsNullOrEmpty(EntityTag)) { return; } var etag = EntityTagHeaderValue.Parse(EntityTag); headers.IfNoneMatch.Add(etag); });
public async Task Patch_Returns_PreconditionFailed_WithOriginalValue_IfVersionMismatch() { TestEntity entity = CreateTestEntity(); string stringValue = entity.StringValue; int intValue = entity.IntValue; Uri location; // create a new entity to update using (HttpResponseMessage postResponse = await this.testClient.PostAsJsonAsync(Address, entity)) { Assert.Equal(HttpStatusCode.Created, postResponse.StatusCode); location = postResponse.Headers.Location; } // Update some properties TestEntitySimple patchEntity = new TestEntitySimple { Id = entity.Id, StringValue = "Updated", IntValue = 84 }; HttpRequestMessage patchRequest = new HttpRequestMessage { RequestUri = location, Method = new HttpMethod("PATCH"), Content = (HttpContent) new ObjectContent <TestEntitySimple>(patchEntity, this.config.Formatters.JsonFormatter) }; patchRequest.Headers.IfMatch.Add(EntityTagHeaderValue.Parse("\"QUJDREVG\"")); using (HttpResponseMessage patchResponse = await this.testClient.SendAsync(patchRequest)) { TestEntity conflict = await patchResponse.Content.ReadAsAsync <TestEntity>(); Assert.Equal(HttpStatusCode.PreconditionFailed, patchResponse.StatusCode); Assert.NotNull(conflict.CreatedAt); Assert.NotNull(conflict.UpdatedAt); } // Query the entity back using location header value to ensure it was *not* updated UriBuilder queryUri = new UriBuilder(location) { }; using (HttpResponseMessage response = await this.testClient.GetAsync(queryUri.Uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestEntity result = await response.Content.ReadAsAsync <TestEntity>(); Assert.Equal(stringValue, result.StringValue); Assert.Equal(intValue, result.IntValue); Assert.NotNull(result.CreatedAt); Assert.NotNull(result.UpdatedAt); } }
protected override async Task When() { _feed = await GetJson <JObject>(TestStream, accept : ContentType.AtomJson); var etag = _feed.Value <string>("eTag"); var headers = new NameValueCollection { { "If-None-Match", EntityTagHeaderValue.Parse($@"""{etag}""").Tag } }; _feed = await GetJson <JObject>(TestStream, accept : ContentType.AtomJson, headers : headers); }
/// <inheritdoc /> public EntityTagHeaderValue Generate(string requestUrl, string responseBody) { byte[] buffer = Encoding.UTF8.GetBytes(requestUrl + "|" + responseBody); using HashAlgorithm hashAlgorithm = MD5.Create(); byte[] hash = hashAlgorithm.ComputeHash(buffer); string eTagValue = "\"" + ByteArrayToHex(hash) + "\""; return(EntityTagHeaderValue.Parse(eTagValue)); }
public async Task<IActionResult> GetPersonByIdAsync([FromRoute] PersonQueryObject query) { var person = await _getByIdUseCase.ExecuteAsync(query).ConfigureAwait(false); if (null == person) return NotFound(query.Id); var eTag = string.Empty; if (person.VersionNumber.HasValue) eTag = person.VersionNumber.ToString(); HttpContext.Response.Headers.Add(HeaderConstants.ETag, EntityTagHeaderValue.Parse($"\"{eTag}\"").Tag); return Ok(_responseFactory.ToResponse(person)); }
public void Parse() { var res = EntityTagHeaderValue.Parse("\"c\""); Assert.AreEqual("\"c\"", res.Tag, "#1"); Assert.IsFalse(res.IsWeak, "#2"); Assert.AreEqual("\"c\"", res.ToString(), "#3"); res = EntityTagHeaderValue.Parse("W/ \"mm\""); Assert.AreEqual("\"mm\"", res.Tag, "#11"); Assert.IsTrue(res.IsWeak, "#12"); Assert.AreEqual("W/\"mm\"", res.ToString(), "#13"); }
public void GetVersionFromIfMatch_ThrowsOnWeakETag() { this.request.Headers.IfMatch.Add(EntityTagHeaderValue.Parse("W/\"abcdef\"")); // Act HttpResponseException ex = Assert.Throws <HttpResponseException>(() => this.request.GetVersionFromIfMatch()); HttpError error; ex.Response.TryGetContentValue <HttpError>(out error); // Assert Assert.Equal("The HTTP If-Match header is invalid: 'W/\"abcdef\"'. Updating an existing resource requires a single, strong ETag, or a wildcard ETag.", error.Message); }
public IActionResult DownloadFile([FromQuery] string path, CancellationToken cancellationToken) { var file = new FileInfo(path); if (file.Exists) { var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); var result = File(fileStream, ContentTypes.Binary, file.Name); result.EnableRangeProcessing = true; result.LastModified = file.LastWriteTimeUtc; result.EntityTag = EntityTagHeaderValue.Parse("\"" + file.Length + "\""); return(result); } return(NotFound()); }
public void AddETagResponseHeader_FindsETag(HttpContent content, string expected) { // Arrange EntityTagHeaderValue expectedETag = expected != null?EntityTagHeaderValue.Parse(expected) : null; HttpResponseMessage response = new HttpResponseMessage() { Content = content }; // Act TableQueryFilter.AddETagResponseHeader(response); EntityTagHeaderValue etag = response.Headers.ETag; // Assert Assert.Equal(expectedETag, etag); }
public async Task <IActionResult> DownloadRequest([FromQuery] DownloadRequest request) { //check if try { var data = await documentService.Load(Address.Of(request.Sender), Signature.Of(request.Signature), Hash.Of(request.Hash)); var mime = MimeTypes.GetMimeType(data.Name); EntityTagHeaderValue entityTag = EntityTagHeaderValue.Parse("\"" + data.Hash.ToHexWithoutPrefix() + "\""); return(base.File(data.Data, mime, data.Name, data.CreatedOn, entityTag)); } catch (InvalidSignatureException ex) { return(base.BadRequest("Invalid signature")); } catch (UnAuthorizedAccessException ex) { return(base.Unauthorized()); } catch (NotFoundException ex) { return(base.NotFound(request.Hash)); } }
public static MockHttpResponseMessage WithEtag(this MockHttpResponseMessage response, string etag) { if (!string.IsNullOrWhiteSpace(etag)) { if (!etag.StartsWith("\"")) { etag = $"\"{etag}\""; } response.Headers.ETag = EntityTagHeaderValue.Parse(etag); } else { response.Headers.ETag = null; } return(response); }
public void Parse_Invalid() { try { EntityTagHeaderValue.Parse(null); Assert.Fail("#1"); } catch (FormatException) { } try { EntityTagHeaderValue.Parse(" "); Assert.Fail("#2"); } catch (FormatException) { } try { EntityTagHeaderValue.Parse("W / \"a\""); Assert.Fail("#3"); } catch (FormatException) { } }
public async Task Replace_CallsDomainManagerWithNonWildcardETag() { // Arrange string order = string.Empty; this.controller.Request.Headers.IfMatch.Add(EntityTagHeaderValue.Parse("\"SGVsbG8=\"")); this.domainManagerMock.Setup(d => d.ReplaceAsync(Id, this.data)) .Callback <string, TestEntity>((id, data) => { Assert.Equal(Encoding.UTF8.GetBytes("Hello"), data.Version); order += "1"; }) .ReturnsAsync(null); // Act await this.controller.ReplaceAsync(Id, this.data); // Assert Assert.Equal("1", order); }
public async Task <object> File( [Required] long id, [FromServices] HashFileProvider fileProvider, [FromServices] AppDbContext context) { var music = await context.Musics.FindAsync(id); if (music is null || music.Deleted) { return(StatusCode(404)); } if (music.Locked) { return(StatusCode(403)); } var fs = fileProvider.GetFileByHash(music.FileHash); return(File(fs, "audio/mp3", music.Title + ".mp3", null, EntityTagHeaderValue.Parse(new StringSegment('"' + music.FileHash + '"')), true)); }
/// <summary> /// /// </summary> /// <param name="actionContext"></param> public override void OnActionExecuting(HttpActionContext actionContext) { var request = actionContext.Request; if (!HttpMethod.Get.Equals(request.Method)) { return; //仅支持get请求 } var key = GetCacheKey(actionContext); request.Properties[ApiCachePropertiesKey] = key; var cachedData = Provider.Get(key) as CachedData; if (cachedData == null) { return; //未命中 } if (request.Headers.IfNoneMatch != null) { if (request.Headers.IfNoneMatch.Any(p => p.Tag == cachedData.Etag)) { actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.NotModified); SetCacheHeader(actionContext.Response, cachedData.CreateAt.AddSeconds(Duration)); return; } } var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK); response.Content = new ByteArrayContent(cachedData.ContentData); response.Content.Headers.ContentType = new MediaTypeHeaderValue(cachedData.MediaType); actionContext.Response = response; if (Location != ApiCacheLocation.Server) { SetCacheHeader(actionContext.Response, cachedData.CreateAt.AddSeconds(Duration)); actionContext.Response.Headers.ETag = EntityTagHeaderValue.Parse(cachedData.Etag); } }