Reputation: 1245
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");
Upvotes: 1
Views: 1352
Reputation: 247521
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");
Upvotes: 2