Home > Net >  Call .Net controller action from JS file
Call .Net controller action from JS file

Time:02-03

I'm trying to reach this action method in Apicontroller, but it is never reached. Instead I get the 404 error.

This is the JS file

function getToken(params) {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: '/api/GetToken',
            type: 'POST',
            contentType: 'text/plain',
            data: params,
            success: launchParams => {
                resolve(launchParams);
            },
            error: err => {
                console.log('Error in getting token!', err);
                reject(err);
            }
        });
    });
}

And this is my action method

[Route("api")]
[ApiController]
public class ApiController : ControllerBase
{
    //other actions ...

    [Route("GetToken")]
    [HttpPost]
    [Consumes("text/plain")]
    [Produces("text/plain")]
    public async Task<JsonResult> GetToken()
    {
        //some code...
    }
}

Note: I'm using razor pages, the JS function is used for all my pages to get the token.

CodePudding user response:

If you are using ApiController in a razor page project,you need to configure routing like this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ...
    app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
}

So that your ApiController will be called.

  •  Tags:  
  • Related