Search code examples
asp.net-core-mvcasp.net-core-6.0

What should I include in my ASP.NET Core 6 MVC application's program.cs?


I've migrated an ASP.NET MVC application to .NET 6 and notice that during testing, the arguments to an action method/controller uses query string rather than the usual REST-style URL.

For example, where the existing ASP.NET MVC 4 application would use the following style of URL

http://webserver/controller/action/123

the migrated web application uses

http://webserver/controller/action?id=123

I created the migrated app from scratch using the template for an ASP.NET Core 6 MVC application.

The program.cs is as follows:

public static void Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);

    builder.Services.AddControllersWithViews();

    var configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .Build();

    // doesn't affect the app if it isn't hosted on IIS
    builder.WebHost.UseIIS();
    builder.WebHost.UseIISIntegration();

    builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();

    builder.Services.AddAuthorization(options => 
    {
        // By default, all incoming requests will be authorized according to the default policy.
        options.FallbackPolicy = options.DefaultPolicy;
    });

    builder.Services
        .AddControllers()
        .AddMvcOptions(opts =>
        {
            opts.MaxModelBindingCollectionSize = 10000;
        });

    builder.Services
        .AddRazorPages()
        .AddRazorRuntimeCompilation();

    var app = builder.Build();

    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Home/Error");
    }
    app.UseStaticFiles();
    app.UseAuthentication();
    app.UseRouting();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
    });

    try
    {
        Log.Information("Application starting up");
        app.Run();
    }
    catch (Exception ex)
    {
        Log.Fatal(ex, "Application startup failed");
    }
    finally
    {
        Log.CloseAndFlush();
    }
}

The Home view renders links to the other controllers using Html helpers such as

@Html.ActionLink("Vendors", "Index", "VendorController", new { @Id = 15153, @Code = "AGR3" }, null)

and the VendorController action method is

[HttpGet]
public ActionResult Index(int id, string code)
{
    // model is a POCO class
    var model = _dataService.GetVendorInfo(id, code);

    return View("Index", model);
}

How do I get my migrated ASP.NET Core MVC application to not use query string for passing arguments? Do I need to decorate the action method with some kind of routing attribute? I thought I could rely on convention-based routing as per the route pattern declared in the call to app.UseEndpoint in the Main() method of Program.cs?


Solution

  • In asp.net core,you could regist mutipule route patterns

    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    
    app.MapControllerRoute(
        name: "myfirstroute",
        pattern: "{controller}/{action}/{id?}/{Code?}");
    
    app.MapControllerRoute(
        name: "mysecondroute",
        pattern: "{controller}/{action}/{id?}");
    

    Specific the name of the route parttern with asp-route and add the required routedata as below(if your dictionary contains the key-values pairs whose key was not registed as a section in your route pattern,it would be added to the query part)

    @{
        var routedatadic = new Dictionary<string,string>();
        routedatadic.Add("controller", "Vendor");
        routedatadic.Add("action", "Index");
        routedatadic.Add("id", "123");
        routedatadic.Add("Code", "ABC");
    }
    
    <a  asp-route="myfirstroute" asp-all-route-data="@routedatadic">Vendor1</a>
    
    <a  asp-route="mysecondroute" asp-all-route-data="@routedatadic">Vendor2</a>
    

    The result: enter image description here

    You could check the document related