miechooy
miechooy

Reputation: 3422

ASP.NET Core Middleware

I have build custom Identity Middle-ware. Inside Invoke method I am checking if request has token etc. After token is checked I want to pass request further to controller. It`s working for GET request - it jump into controller method. It is not working for POST request.

Here is Invoke Method

public async Task Invoke(HttpContext context)
{
    //checking
    await _next(context);
}

Its working controller:

[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET api/values
    [AllowAnonymous]
    [HttpGet]
    public string Get()
    {
        return "Allow annymous";
    }
 }

And not working one

[Route("api/[controller]")]
public class AccountController : Controller
{
    [AllowAnonymous]
    [HttpPost]
    public void Login()
    {
         //some logic
          HttpContext.Response.WriteAsync("Unauthorized");
    }
}

Making POST call Postman returns 404 not found.

Upvotes: 3

Views: 1724

Answers (3)

Vedant
Vedant

Reputation: 203

Looking at your code I hopping there is only one method inside the AccountController called Login. If not please add attribute [Route("Login")] to Login method (make sure you do not keep it empty like [Route("Login")] otherwise it will have same as what you are doing currently).

Then make the call to the POST http://host:***/api/account/login url and that should work.

FYI: I have tried this thing on my machine and it is working.

Upvotes: 0

juunas
juunas

Reputation: 58723

The route for the action in question would be /api/Account. Make sure that is correct.

If instead you wanted /api/Account/Login:

[Route("api/[controller]/[action]")]
public class AccountController : Controller
{
    [AllowAnonymous]
    [HttpPost]
    public void Login()
    {
         //some logic
          HttpContext.Response.WriteAsync("Unauthorized");
    }
}

Upvotes: 1

Alexander Staroselsky
Alexander Staroselsky

Reputation: 38757

Try returning something like an IActionResult rather than simply void.

[AllowAnonymous]
[HttpPost]
public IActionResult Login() 
{
    // some logic
    return Unauthorized();
}

Upvotes: 0

Related Questions