当前位置:网站首页>Shallow understanding Net core routing

Shallow understanding Net core routing

2022-07-07 16:59:00 Old sentencing

route :

web When your request arrives at the back-end service ,controller( controller ) Will process incoming http Request and respond to user actions , Requested url Will be mapped to the operation method of the controller .

This mapping process is done by the routing rules defined in the application .

 ASP.NET.Core MVC The routing

Routing uses a pair of UseRouting and UseEndPoints Registered middleware :

UseRouting Add route matching to middleware pipeline . This middleware will view the endpoint set defined in the application , And select the best match according to the request

UseEndpoints Add endpoint execution to the middleware pipeline .

asp.net.core There are two routing technologies : General routing and attribute routing

General routing :

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseStaticFiles();

    app.UseMvcWithDefaultRoute();
}

Default routing template {controller=Home}/{action = Index}/{id?}, Most of the URL Will map according to this rule . Question mark id Parameters are optional .

  If you want to define your own path template , To use UseMvc() Method , instead of UseMvcWithDefaultRoute() Method .

app.UseMvc(routes =>
{
    routes.MapRoute("default","{controller=Home}/{action = Index}/{id?}");
});

 

//1、 Enable default routing 
app.UseStaticFiles();
app.UseRouting();  
app.UseMvcWithDefaultRoute();
            
 
 
//2、 Custom routing template 
app.UseStaticFiles();
app.UseRouting();
app.UseMvc(routes =>
{
    routes.MapRoute(
    name: "default",
    template: "{controller=Home}/{action=Index}/{id?}");
});
 
//3、 Use UseEndpoints Custom routing template  
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
   endpoints.MapControllerRoute(
   name: "default",
   pattern: "{controller=Home}/{action=Index}/{id?}");
 
});

Attribute routing :

Use attribute routing , Can be in Controller or Controller The operation method of Route attribute .

stay Startp.cs file Configure In the method , We only use app.UseMvc(); And then in Controller Of Action Methodically, through features Route To configure the .

 [Route("[controller]/[action]")]
    public class HomeController : Controller
    {
        private readonly IStudentRepository _studentRepository;
        // Constructor injection 
        public HomeController(IStudentRepository studentRepository)
        {
            _studentRepository = studentRepository;
        }

        [Route("")]
        [Route("~/")] // solve  http://localhost:44338/  Can't access the problem 
        [Route("~/home")] // solve  http://localhost:44338/home  Can't access the problem 
        public IActionResult Index(int id)
        {
            return Json(_studentRepository.GetStudent(id));
        }

        [Route("{id?}")]
        public IActionResult Details(int? id)
        {
            Student model = _studentRepository.GetStudent(id??1);
            return View(model);
        }

        public ObjectResult detail()
        {
            return new ObjectResult(_studentRepository.GetStudent(1));
        }
    }

Examples used in practical projects --- Download the file

[ApiExplorerSettings(IgnoreApi = true)]
    public class DownFileController : Controller
    {
        private ILogger _logger;

        /// <summary>
        ///  download Pscan file 
        /// </summary>
        /// <param name="taskId"></param>
        /// <param name="DownloadFilePath"></param>
        /// <param name="fileNameList"></param>
        /// <returns></returns>
        [Route("[Controller]/{taskId}/{DownloadFilePath?}/{fileName?}")]
        public IActionResult GetDownFileMessage(string taskId, string DownloadFilePath, string fileName)
        {
            try
            {

                if (fileName != null)
                {
                   
                  
                    // Remote deployment 
                    //string path = "/home/ftp_flow/Data/TaskData/" + taskId + "/" + DownloadFilePath;
                    //string zipPath = "/Data/PscanDownFile/" + $"{DownloadFilePath+"/"+fileNameList}.zip";

                    // Local debugging 
                    string path = @"E:\beijingData\TaskData\" + taskId + "/" + DownloadFilePath;
                    
                    Console.WriteLine(path);
                  
                    var filePath = Path.Combine(path, fileName);
                    if (System.IO.File.Exists(filePath))
                    {
                        Console.WriteLine(filePath);
                        string fileExt = Path.GetExtension(filePath);
                        // retrievable ContentType
                        var provider = new FileExtensionContentTypeProvider();
                        var memi = provider.Mappings[fileExt];
                        var stream = System.IO.File.OpenRead(filePath);
                        Console.WriteLine("success");
                        return File(stream, memi, Path.GetFileName(filePath));


                    }
                    else
                    {
                        return NotFound();
                    }
                  
                }
                else
                {
                    return NotFound();
                }

            }
            catch (Exception ex)
            {
                return NotFound();
            }
        }
    }

原网站

版权声明
本文为[Old sentencing]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071510056538.html