Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net core how to add Content-range to header

I'm having no luck find out how to add Content-Range to the header of my odata requests. My api requires a format as such for paging:

Content-Range: posts 0-24/319

The closest thing I can find is HTTP Byte Range Support. From here: https://blogs.msdn.microsoft.com/webdev/2012/11/23/asp-net-web-api-and-http-byte-range-support/ . The OP says a post will be written about [Queryable] which is supposed to add support for paging, but I have yet to see any info on this.

        [EnableQuery]
        [ODataRoute]
        public IActionResult Get(ODataQueryOptions<HC_PortalActivity> 
         options)
        {

            return Ok(Db.HC_PortalActivity_Collection);
        }
like image 526
Jesse Avatar asked Oct 23 '25 04:10

Jesse


2 Answers

You can add the Content-Range header to your HttpRequest.Content object:

request.Content.Headers.ContentRange = new System.Net.Http.Headers.ContentRangeHeaderValue(0, 24, 319);

request.Content.Headers.ContentRange.Unit = "posts";

Remember to set the Unit otherwise it will default to `bytes'

EDIT

The Content property is only available on the HttpRequestMessage class, not the HttpRequest class. So you will need to create one to be able to access the ContentRange property.

var request = new HttpRequestMessage();
... // as above

Assuming you are using a HttpClient to send your request you can pass the request in the SendAsync method

var httpClient = new HttpClient();
... // other setup

httpClient.SendAsync(request);
like image 52
Simply Ged Avatar answered Oct 25 '25 06:10

Simply Ged


Here is what I ended up doing:

  public static void IncludeContentRange<T>(ODataQueryOptions<T> options, HttpRequest context)
        {
            var range = options.Request.Query["range"][0].Replace("[", "").Replace("]", "").Split(',');
            var q = from x in Db.HC_PortalActivity_Collection
                    select x;

            var headerValue = string.Format("{0} {1}-{2}/{3}", options.Context.NavigationSource.Name.ToLower(), range[0], range[1], q.Count());
            context.HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Range");
            context.HttpContext.Response.Headers.Add("Content-Range", headerValue);
        }
like image 26
Jesse Avatar answered Oct 25 '25 08:10

Jesse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!