Sachin Singh

Sachin Singh

  • 7
  • 55.8k
  • 81.4k

How to get Location Header in jquery success in a cross origin request

Sep 3 2020 2:45 AM
the web api post method is setting location header like below
  1. public HttpResponseMessage Post([FromBody]Employee emp)  
  2.       {  
  3.           try  
  4.           {  
  5.               db.Employees.Add(emp);  
  6.               db.SaveChanges();  
  7.               var msg = Request.CreateResponse(HttpStatusCode.Created, emp);  
  8.               msg.Headers.Location = new Uri(Request.RequestUri +"/"+ emp.Id.ToString());  
  9.               return msg;  
  10.           }  
  11.           catch  
  12.           {  
  13.               return new HttpResponseMessage(HttpStatusCode.InternalServerError);  
  14.           }  
  15.       } 
 fiddler successfully recognized the location
 
 
 
Its a cross origin request , so xhr doesn't include all headers untill you force it to set additional headers in "Access-Control-Expose-Headers"  , so i had to set this like below
  1. $.ajax({  
  2.                  
  3.                 "type""Post",  
  4.                 "url": myUrl,  
  5.                 "dataType""json",  
  6.                 
  7.                 "contentType""application/json;charset=utf-8",  
  8.                 "data": JSON.stringify(model),  
  9.                 "traditional"true,  
  10.                 "dataTpe""Json",  
  11.                 "headers": {  
  12.                     
  13.                     "Access-Control-Expose-Headers""location",  
  14.                 },  
  15.                 "cache"false,  
  16.                 "crossDomain"true,  
  17.                 "success"function (data,status,xhr) {  
  18.                     debugger;  
  19.   
  20.                     alert(xhr.getResponseHeader('Location'));  
  21.                 },  
  22.   
  23.                 "error"function (request, message, error) {  
  24.                     handleException(request, message, error);  
  25.                 } 
 but no luck , getting null in alert.

Answers (2)