首页 > 解决方案 > Javascript redirect (window.location.href) doesn't work in an Asp.NET Core project when called from an EventListener function

问题描述

So upon clicking button the script sends a POST request, which is correctly processed and the following response is sent

redirectUrl = Request.Host + "/" + page.PageURL;
return Json(new { url = redirectUrl });

The above described process is initiated by the following code

var request = new XMLHttpRequest();
request.open("POST", "/Page/Upload");
request.send(formData);
handleRequestSent(request);

The part below properly parses the return Json and gives the proper url (localhost:5001/pagename)

 function handleRequestSent(request) {
    request.addEventListener("readystatechange", function () {
        console.log(this);
        if (this.readyState === 4) {
            var responseData = JSON.parse(this.responseText);
            console.log(responseData.url);
            redirectToPage(responseData.url);
        };
    });
}

This is the part that doesn't work. But it only seems not to work when called from the above code. When I called this method directly it redirected me to the indicated address.

function redirectToPage(redirectUrl) {
    window.location.href = redirectUrl;
}

I have also tried various other forms that do the same thing as window.location.href but none of them worked. What's going on here?

标签: javascriptc#asp.netasp.net-core

解决方案


You forget to add request scheme to the redirectUrl:

redirectUrl =  Request.Scheme + "://" + Request.Host + "/" + page.PageURL;

推荐阅读