简体   繁体   中英

.NET Framework 4.6.2 Unable to hit POST endpoint

I created a .NET Framework 4.6.2 WEB API, in my AuthController I created a test endpoint that will accept a parameter. I am unable to hit this endpoint. The error I get is: "MessageDetail": "No action was found on the controller 'Auth' that matches the name 'Test'."

EndPoint:

    [Route("api/auth")]
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class AuthController : ApiController, IDisposable
    {
        [HttpPost]
        [Route("Test")]
        public HttpResponseMessage Test([FromBody] object response)
        {
           return Request.CreateResponse(HttpStatusCode.OK, "Success");
        }
     }

My Log In Function:

function LogIn() {

InputData = {
    UserName: $("#Login_UserName").val(),
    Password: $('#Login_Password').val()
};

console.log($("#Login_UserName").val());
console.log(InputData);

$.ajax({
    type: "post",
    url: 'https://localhost:44393' + '/api/auth/test',
    contentType: 'application/json',
    data: JSON.stringify(InputData),
    success: function (data) {
        HideSmokeLoader();
        console.log(data);
    },
    error: function (request) {
        console.log(request)
    }
});

}

Try changing the Route attribute in your controller to RoutePrefix. So:

    [RoutePrefix("api/auth")]
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class AuthController : ApiController, IDisposable

Made a new project and set it up just the same as you. Then used postman to call the endpoint and got the same "No action was found...". The Route attribute is the full path to the Action - so if you were to call https://localhost:44393/Test you will reach the controller.

Add your Route on the Action itself like this -

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class AuthController : ApiController, IDisposable
{
    [HttpPost]
    [Route("api/auth/test")]
    public HttpResponseMessage Test([FromBody] object response)
    {
       return Request.CreateResponse(HttpStatusCode.OK, "Success");
    }
 }

change [Route("api/auth")] to [RoutePrefix("api/auth")] because RouteAttribute Place on a controller or action to expose it directly via a route. When placed on a controller, it applies to actions that do not have any System.Web.Mvc.RouteAttribute's on them.

RoutePrefixAttribute

Annotates a controller with a route prefix that applies to all actions within the controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM