Tengo un proyecto .NET Core 3.1 que usa Razor Pages . A partir de él, creé una prueba simple en la que puedo realizar una llamada Ajax exitosa con el siguiente código:
Índice.cshtml.cs
public class IndexModel : PageModel { public void OnGet() { } public JsonResult OnGetTest() { return new JsonResult("Ajax Test"); } }Índice.cshtml
@page @model IndexModel <div class="text-center"> <p>Click <a href="#" onclick="ajaxTest()">here</a> for ajax test.</p> </div> <script type="text/javascript"> function ajaxTest() { $.ajax({ type: "GET", url: "/Index?handler=Test", contentType: "application/json; charset=utf-8", dataType: "json", error: function (xhr, status, error) { console.log(error); } }).done(function (data) { console.log(data); }); } </script> Sin embargo, me gustaría sacar el método Ajax de la Razor Page y colocarlo en un Controller para poder llamarlo desde varias Razor Pages . He creado un controlador usando el siguiente código:
public class AjaxController : Controller { public JsonResult Test() { return new JsonResult("Ajax Test"); } }Inicio.cs
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { options.EnableEndpointRouting = false; }); services.AddRazorPages(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseMvcWithDefaultRoute(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } } Pero cualquiera que sea el valor que use en la url para la llamada Ajax, obtengo un 404 error . ¿La carpeta Controllers debe estar en el directorio Pages ? ¿O necesito configurar algún enrutamiento para usar un Controller con Razor Pages ?
url: "/Ajax/Test" // <-- What goes here?Aquí está la estructura de directorios actual:
Debe especificar un atributo de Route , como este:
[Route("api/Ajax")] public class AjaxController : Controller { // ... }También es mejor decorar cada punto final individual con un atributo 'Método', como este:
[HttpGet] public JsonResult Test() { return new JsonResult("Ajax Test"); } Además, también debe establecer la configuración correcta en Startup.cs como se muestra a continuación, agregue todas las partes que no tiene:
public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { options.EnableEndpointRouting = false; }); services.AddRazorPages(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // lots of stuff... // I have this after app.UseStaticFiles(), it may also work elsewhere app.UseMvcWithDefaultRoute(); // lots of other stuff... } Y luego debería poder llamarlo usando la ruta /api/Ajax/Test .
En Startup.cs, agregue esto a ConfigureServices()
services.AddMvc(options => options.EnableEndpointRouting = false);En Startupcs, también agregue esto a Configure ()
app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); });DisplayController.cs
public IActionResult Test() { return new JsonResult("Hi World"); }Índice.cshtml
<a onclick="ClickMe();">Click Me</a> <script> function ClickMe() { $.get("/Display/Test", null, function (e) { alert(e); }); } </script>