locked
Redirect to external url not working RRS feed

  • Question

  • User-1674296013 posted

    hi,I am running on asp.net.core 3.1 ,When I click the button its return from origin 'http://localhost:49985' has been blocked by CORS policy

    <div>   
    
    <input type="button" value="Redirect" class="btn btn-primary mt-5 ml-5"  id="btnGo" name="btnGo" /> 
    
    </div>
    
    <script type="text/javascript">
       
        $('#btnGo').on("click", function () {
            $.ajax({           
                url: "/Respond/test",
                type: 'Post',            
                cache:false            
            });
        });
    
    </script>
    
    [HttpPost]
     public RedirectResult test()
        {     
    
         return Redirect("http://www.google.com");
        }
    
    Startup.cs
    
    services.AddMvc();      
    services.AddCors(c =>
          {
            c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader()
            );
          });
    
    
    app.UseRouting();
    app.UseStaticFiles();
           
          app.UseCors("AllowAllOrigins");
    
       app.UseEndpoints(endpoints =>
          {
            endpoints.MapControllerRoute(
                      name: "default",
                      pattern: "{controller}/{action}/{id?}");
          });
    
    
    Sunday, December 20, 2020 10:57 AM

Answers

  • User475983607 posted

    The code you shared is missing quotes.  The code below redirects. 

    public IActionResult Goo()
    {
        return Content("window.location.href = 'http://www.google.com'", "application/x-javascript; charset=utf-8");
    }
    @{
        ViewData["Title"] = "Index";
    }
    
    <h1>Index</h1>
    
    <button class="redirect">
        Redirect
    </button>
    
    
    
    @section Scripts {
        <script>
        $('.redirect').click(function () {
    
            $.ajax({
                type: 'post',
                url: '@Url.Action("Goo")'
            });
    
        });
        </script>
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, December 21, 2020 7:48 PM

All replies

  • User-2054057000 posted

    Use the below code to redirect from JavaScript.

    window.location.replace("https://www.google.com")

    For redirction in asp.net core use the below code (refer Performing Redirections in Action Methods)

    RedirectPermanent("https://www.google.com");
    Sunday, December 20, 2020 11:32 AM
  • User-474980206 posted

    Because it an Ajax call, the results of the url is returned as data to the success. As the request redirected, it broke the CORS policy, as the Ajax call had to call another their server.

    if you are excepting the the Ajax call to return a call redirect, either use a form post to begin with, or return the redirect url in response json payload. Then the success callback can redirect by using the location object.

    Sunday, December 20, 2020 7:56 PM
  • User1312693872 posted

    Hi,alya14

    You can use ajax success to redirect:


    <script type="text/javascript"> $('#btnGo').on("click", function () { $.ajax({ url: "/Home/test", type: 'Post', success: function () { window.location.href = "http://www.google.com/"; } }); }); </script>

    And in controller, you can still run code in it:

    [HttpPost]
            public IActionResult test()
            {
                //code that you want to run
                return NoContent();
            }

    But if you just want to redirect after clicking the button, you can just use this way:

    <script type="text/javascript">
            $('#btnGo').on("click", function () {
                window.location.href = "http://www.google.com/";
            });
    </script>

    Best Regards,

    Jerry Cai

    Monday, December 21, 2020 3:10 AM
  • User-1674296013 posted


    Hi Jerry Cai ,I can't do it due to ,I am wonder to some naughty clients change to this settings from client side

    Monday, December 21, 2020 10:53 AM
  • User-1674296013 posted

    Hi Bruce,

    Normally I can do it with Asp.Net MVC like below , But Net.Core not doesn't know the syntax 

    return JavaScript("window.location.href = http://www.google.com");

      [HttpPost]
    public JavaScriptResult()
    {
    return JavaScript("window.location.href = http://www.google.com");
    }

    Monday, December 21, 2020 10:56 AM
  • User-1674296013 posted

    Use the below code to redirect from JavaScript.

    window.location.replace("https://www.google.com")

    For redirction in asp.net core use the below code (refer Performing Redirections in Action Methods)

    RedirectPermanent("https://www.google.com");

    RedirectPermanent return error has been blocked Cors policy.

    Monday, December 21, 2020 11:00 AM
  • User475983607 posted

    IMHO, it makes little sense to redirect from JavaScript.  A standard post directly to the URL will work which saves an HTTP request.

    <form method="post" id="myform" name="myform" action="/Respond/test">
        <div>
            <input type="submit" name="submit" />
        </div>
    </form>

    You can also use a link but it requires a little JavaScript to submit a form programmatically.

        <script>
            function DoPost() {
                document.forms["myform"].submit();
            }
        </script>

    Monday, December 21, 2020 12:38 PM
  • User-1674296013 posted

    IMHO, it makes little sense to redirect from JavaScript.  I standard post will work which saves an entire HTTP request.

    <form method="post" id="myform" name="myform" action="/Respond/test">
        <div>
            <input type="submit" name="submit" />
        </div>
    </form>

    You can also use a link but it requires a little JavaScript to submit the same form.

        <script>
            function DoPost() {
                document.forms["myform"].submit();
            }
        </script>


    hi ,
    I alrady can do like below

    @using (Html.BeginForm("Goo", "Respond", null, FormMethod.Post))
        {
          <input type="submit" value="Redirect" class="btn btn-primary mt-5 ml-5"  id="btnGo" name="btnGo" />
        }
    But I want to do like that I asked first post , I think some of middleware config is missing ,so its blocked by cors.
    Monday, December 21, 2020 1:16 PM
  • User475983607 posted

    But I want to do like that I asked first post , I think some of middleware config is missing ,so its blocked by cors.

    The official documentation illustrates how to enable CORS.  

    https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0

    You must enable CORS on the cross-origin application not the application that rendered the original HTML.

    Keep in mind, enabling CORS will not fix the design bug shown in the original post.  Plus, returning a JavaScript result is considered an anti-pattern because it creates a dependency between the View and the Controller.  This is why ASP.NET Core does not have this feature.

    Anyway, you can create a hack to do the same as a JavaScriptResult by returning a JavaScript content type.

    return Content("window.location.href = http://www.google.com", "application/x-javascript; charset=utf-8");

    Monday, December 21, 2020 2:24 PM
  • User-1674296013 posted

    return Content("window.location.href = http://www.google.com", "application/x-javascript; charset=utf-8");

    for use this

    return Content("window.location.href = http://www.google.com", "application/x-javascript; charset=utf-8");

    I need to create public ContentResult and after do this nothing change.
    Monday, December 21, 2020 5:06 PM
  • User475983607 posted

    I'm not sure how to help you.  The code I shared is exactly the same as your JavaScriptResults example.

    Monday, December 21, 2020 5:50 PM
  • User-1674296013 posted

    mgebhard

    I'm not sure how to help you.  The code I shared is exactly the same as your JavaScriptResults example.

    Normally I can do it with Asp.Net MVC like below 
    
    [HttpPost]
    public JavaScriptResult Goo()
    {
    return JavaScript("window.location.href = http://www.google.com");
    }
    
    $.ajax({
    url: "/Respond/Goo",
    type: 'POST'
    cache: false,
    contentType: false,
    processData: false
    
    });
    
    But Net.Core not doesn't know the syntax 
    
    return JavaScript("window.location.href = http://www.google.com");
    
    I think I will try to submit form by js.



    Monday, December 21, 2020 6:29 PM
  • User753101303 posted

    Hi,

    It seems you expect the browser will process the redirect or will run the returned JavaScript code. But the whole purpose of Ajax is precisely to takje full programmatic control of the request and its response without the browser doing anything itself.

    Not sure on which even you run this but for now it seems an hyperlink could be enough (your button doesn't even post any data but is just supposed to redirect the browser to a new location?)

    Monday, December 21, 2020 7:13 PM
  • User475983607 posted

    The code you shared is missing quotes.  The code below redirects. 

    public IActionResult Goo()
    {
        return Content("window.location.href = 'http://www.google.com'", "application/x-javascript; charset=utf-8");
    }
    @{
        ViewData["Title"] = "Index";
    }
    
    <h1>Index</h1>
    
    <button class="redirect">
        Redirect
    </button>
    
    
    
    @section Scripts {
        <script>
        $('.redirect').click(function () {
    
            $.ajax({
                type: 'post',
                url: '@Url.Action("Goo")'
            });
    
        });
        </script>
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, December 21, 2020 7:48 PM