.net core how to add Content-range to header

◇◆丶佛笑我妖孽 提交于 2020-05-15 21:03:06

问题


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);
        }

回答1:


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);



回答2:


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);
        }


来源:https://stackoverflow.com/questions/53289657/net-core-how-to-add-content-range-to-header

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!