1

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.

4
  • 1
    Can you try commenting out the redirect line in the C# code? Perhaps the redirect is not preserving the header. Commented Oct 4, 2020 at 6:53
  • and what is your sendRequest service using? xhr fetch ? Commented Oct 4, 2020 at 7:18
  • 1
    my sendRequest() service is using fetch Commented Oct 4, 2020 at 8:18
  • 1
    i commentted out the Response.Redirect(), and it is work, thx Commented Oct 4, 2020 at 9:15

1 Answer 1

2

Before returning return Json("Ok"); you are callin Response.Redirect("~/Home/Index"); which is redirecting to new get request instead of returning the response to the current client call.

instead of calling Response.Redirect("~/Home/Index"); before return return Json("Ok"); , you can remove it from server side and handle at the response of ajax request at client-side in javascript function.

please see the below url for your understanding.

https://stackoverflow.com/questions/4070430/response-redirect-with-headers#:~:text=Still%20no%20way%20to%20control,headers%20when%20performing%20a%20redirect.&text=Response.,-Headers.&text=Redirect%2C%20you%20are%20simply%20redirecting,params%20between%20these%20two%20pages.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.