I am trying to send a response with custom header named "x-custom-token" set at server side, and the browser is receiving it. But at client side. I am not able to get it.
This is my server side code (.Net framework).
[AllowAnonymous]
[HttpPost]
//[EnableCors(origins: "*", headers: "*", methods:"*",exposedHeaders: "x-custom-token")]
[AllowCrossSiteAttribute]
//[ValidateAntiForgeryToken]
public ActionResult Login(string account, string password)
{
if (account == null || password == null)
{
throw new ArgumentNullException("account or password is null");
}
try
{
if (this.userService.CheckUserData(account, password))
{
string roleName = this.userService.GetRole(account, password);
string token = this.jWTService.GenerateToken(account, roleName);
Response.AppendHeader("Access-Control-Expose-Headers", "x-custom-token");
Response.AppendHeader("x-custom-token", token);
Response.Redirect("~/Home/Index");
return Json("Ok");
}
else
{
Response.StatusCode = 204;
Response.Redirect("~/Login/login");
return Json("no permission");
}
}
catch (Exception ex)
{
Response.StatusCode = 400;
Response.StatusDescription = ex.Message;
Response.Redirect("~/Login/login");
return Json("no permission");
}
}
And this is client side (Javascript):
const loginButton = document.getElementsByClassName("login")[0];
loginButton.addEventListener("click", async function () {
const account = document.getElementsByClassName("accountInput")[0].value;
const password = document.getElementsByClassName("passwordInput")[0].value;
const body = `account=${account}&password=${password}`;
const re = await sendRequest("/Login/login", "POST", { "Content-Type": "application/x-www-form-urlencoded" }, body);
if (re.status === 200) {
console.log(re);
console.log(re.headers.get("access-control-expose-headers"));
console.log(re.headers.get("x-custom-token"));
console.log(re.headers.get("x-aspnet-version"));
debugger
window.location.href = `${window.location.protocol}//${window.location.hostname}:${Number(44398)}/Home/Index`;
}
else {
alert(`response status: ${re.status} ${re.json()}`);
}
}, false);
In this line of code console.log(re.headers.get("x-custom-token")); I always get null....
the Access-Control-Expose-Headers is also added.
I am sure the browser has the response with this custom header
browser response
This is my sendRequest() method:
async function sendRequest(path, method, headers, body) {
const protocol = window.location.protocol;
const domainName = window.location.hostname;
const port = "44398"
let options = {
method: method,
headers: headers,
}
if (body) {
options.body = body;
}
const response = await fetch(`${protocol}//${domainName}:${port}${path}`, options)
return response;
}
I am trying to figure out what is happening.