C#C
C#4y ago
surwren

[ASP.NET] Middleware Stops Controller From Receiving Login Request

These are my buttons in /Views/Login

    <form role="search" action="/Login/AddLoginCookie" method="POST">
        <button class="btn btn-dark" id="test1" type="submit">Login</button>
    </form>

    <form role="search" action="/Login/DelLoginCookie" method="POST">
        <button class="btn btn-dark" id="test2" type="submit">Logout</button>
    </form>


These are the buttons in /Controllers/LoginController

        [HttpPost]
        public IActionResult AddLoginCookie()
        {

            Response.Cookies.Append("sessionId", "001");
            return RedirectToAction("Index", "Login");
        }

        //works even without HttpPost
        [HttpPost]
        public IActionResult DelLoginCookie()
        {
            Response.Cookies.Delete("sessionId");

            return Redirect(Request.Headers["Referer"].ToString());
        }


This is the middleware code in program.cs

app.Use(async (context, next) =>
{
    if (context.Request.Path.StartsWithSegments("/Login/"))
    {
        await next(context);
        return;
    }

    string sessionId = context.Request.Cookies["sessionId"];
    if (sessionId == null)
    {
        
        context.Response.Redirect("/Login/");
    }
    else
    {
        await next(context);
    }
});


For some reason, it looks like the middleware is preventing the user from using the controller IActionMethods in /LoginController to get a session ID. But this seems to be happening anyway even though I am checking that (context.Request.Path.StartsWithSegments("/Login/")).



FWIW, even

if (context.Request.Path.StartsWithSegments("/Login/AddLoginCookie/"))
will not let me through to the IActionResult.

What is going wrong here?
Was this page helpful?