1
votes

I am wrtiting a web api in .net 6, I am getting data from SQL Server and returning in json format, I want to add some headers in response as well. all headers are working fine except one which contains hyphen.

var data = [data from database]
var response = Request.CreateResponse(HttpStatusCode.OK, data);
response.Headers.Add("transactionid", "working fine");
response.Headers.Add("requesttimestamp", "working fine);
response.Headers.Add("**last-modified**", "does not work");

I am getting this error

Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.

response.Headers.Add("Accept", "application/json");
response.Headers.Add("Content-Type", "application/json; charset=utf-8");

but same error.

I am writing a client as well and trying to add similar parameter in request header but getting a different error

The format of value '15/10/2018 04:30:15 AM' is in correct

var client=new HttpClient();
client.DefaultRequestHeaders.Add("if-last-modified", "15/10/2018 04:30:15 AM");

if I remove hyphens, it works fine.

Update: I fixed it by changing this code

response.Content.Headers.TryAddWithoutValidation("last-modified", lastModified);

and

client.DefaultRequestHeaders.TryAddWithoutValidation("if-modified-since", "15/10/2018 04:30:15 AM");

1
Can you try with HttpContext.Response?Md. Abdul Alim
yes it works that way but adds last-modified as "Last-Modified", can i make it all lower case? but I would prefer Request.CreateResponse method if possibleAli
Last-Modified is content headers not response headers. Try using response.Content.Headers.LastModified to set its value...IronGeek
if Last-Modified is already part of response ok header, then I want to add another last-modified with my own value.Ali
just changed the name of the header to make it clear.Ali

1 Answers

2
votes

Try adding it to the response's content's headers.

response.Content.Headers.TryAddWithoutValidation("X-LAST-MODIFIED", "15/10/2018 04:30:15 AM");

Note the use of TryAddWithoutValidation to avoid validation of the header, which I believe is the cause of your problems.

The same can be done for requests

var client = new HttpClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("X-LAST-MODIFIED", "15/10/2018 04:30:15 AM");