-1

When I redirect the GET method in middleware using asp net core it works fine. But When I want to redirect the post method I accept the method not allowed(405) error. Here is my redirect code in the startup.cs(Configure method):

 app.Use(async (context, next) =>
        {
            var url = context.Request.Path.Value;

            // Redirect to an external URL
            if (url.Contains("/api/auth"))
            {
                context.Response.Redirect("http://localhost:port"+url);
                return;   // short circuit
            }

            await next();
        });

How can I solve it?

Ian Kemp
  • 24,155
  • 16
  • 97
  • 121
M.M
  • 9
  • 2
  • A redirect will usually cause the client (e.g. the browser) to make a GET request instead. You cannot make automatic redirects on POSTs. – poke Oct 03 '20 at 13:55
  • @poke how can I make redirect on POST methods? – M.M Oct 03 '20 at 14:15

1 Answers1

0

You can try to redirect to a HttpGet action in middleware,and in the action redirect to a HttpPost action. Here is a demo:

app.Use(async (context, next) =>

            {
                var url = context.Request.Path.Value;
                if (url.Contains("/api/auth"))
                {
                    context.Response.Redirect("https://localhost:44358/Home/TestGet");
                    return;   // short circuit
                }
                await next();
            });

HomeController:

[HttpGet]
        public IActionResult TestGet() {
            return TestPost();
        }
        [HttpPost]
        public IActionResult TestPost() {
            return Json("Here is a post action");
        }

result: enter image description here

Yiyi You
  • 6,871
  • 1
  • 2
  • 9