当前位置:网站首页>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();
}
}
}
边栏推荐
- Sort out several important Android knowledge and advanced Android development interview questions
- Advanced C language -- function pointer
- LeetCode 1477. Find two subarrays with sum as the target value and no overlap
- LeetCode 1981. Minimize the difference between the target value and the selected element one question per day
- LeetCode 1043. Separate the array to get the maximum and daily questions
- QT视频传输
- 字节跳动高工面试,轻松入门flutter
- QML beginner
- 【DesignMode】代理模式(proxy pattern)
- Spark Tuning (III): persistence reduces secondary queries
猜你喜欢
字节跳动Android金三银四解析,android面试题app
The team of East China Normal University proposed the systematic molecular implementation of convolutional neural network with DNA regulation circuit
Lowcode: four ways to help transportation companies enhance supply chain management
低代码(lowcode)帮助运输公司增强供应链管理的4种方式
字节跳动高工面试,轻松入门flutter
掌握这个提升路径,面试资料分享
Skimage learning (3) -- gamma and log contrast adjustment, histogram equalization, coloring gray images
【DesignMode】代理模式(proxy pattern)
正在准备面试,分享面经
3000 words speak through HTTP cache
随机推荐
LeetCode 1186. 删除一次得到子数组最大和 每日一题
[PHP] PHP interface inheritance and interface multi inheritance principle and implementation method
LeetCode 312. 戳气球 每日一题
Vs2019 configuration matrix library eigen
LeetCode-SQL第一天
DNS 系列(一):为什么更新了 DNS 记录不生效?
The team of East China Normal University proposed the systematic molecular implementation of convolutional neural network with DNA regulation circuit
[C language] question set of X
SqlServer2014+: 创建表的同时创建索引
skimage学习(2)——RGB转灰度、RGB 转 HSV、直方图匹配
Sqlserver2014+: create indexes while creating tables
Cesium (4): the reason why gltf model is very dark after loading
如何选择合适的自动化测试工具?
Direct dry goods, 100% praise
Personal notes of graphics (4)
typescript ts 基础知识之类型声明
Module VI
LeetCode 1049. Weight of the last stone II daily question
【DesignMode】代理模式(proxy pattern)
Master this promotion path and share interview materials