当前位置:网站首页>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();
}
}
}
边栏推荐
- [PHP] PHP interface inheritance and interface multi inheritance principle and implementation method
- LeetCode 1626. 无矛盾的最佳球队 每日一题
- Pychart ide Download
- 字节跳动高工面试,轻松入门flutter
- [designmode] flyweight pattern
- 深度监听 数组深度监听 watch
- Prediction - Grey Prediction
- LeetCode 1155. N ways to roll dice one question per day
- Introduction and use of gateway
- Process from creation to encapsulation of custom controls in QT to toolbar (I): creation of custom controls
猜你喜欢
Temperature sensor chip used in temperature detector
Pycharm terminal enables virtual environment
字节跳动Android面试,知识点总结+面试题解析
Process from creation to encapsulation of custom controls in QT to toolbar (I): creation of custom controls
Three. JS series (1): API structure diagram-1
【DesignMode】代理模式(proxy pattern)
Pisa-Proxy SQL 解析之 Lex & Yacc
Pycharm IDE下载
数据中台落地实施之法
【DesignMode】外观模式 (facade patterns)
随机推荐
掌握这个提升路径,面试资料分享
LeetCode 213. Home raiding II daily question
LeetCode 1049. 最后一块石头的重量 II 每日一题
在哪个期货公司开期货户最安全?
ByteDance Android gold, silver and four analysis, Android interview question app
偶然升职的内心独白
The process of creating custom controls in QT to encapsulating them into toolbars (II): encapsulating custom controls into toolbars
字节跳动高工面试,轻松入门flutter
three. JS create cool snow effect
QT video transmission
Pisa-Proxy SQL 解析之 Lex & Yacc
Introduction and use of gateway
LeetCode 1155. 掷骰子的N种方法 每日一题
QT 图片背景色像素处理法
Personal notes of graphics (1)
AutoLISP series (3): function function 3
LocalStorage和SessionStorage
LeetCode 1031. Maximum sum of two non overlapping subarrays
skimage学习(3)——使灰度滤镜适应 RGB 图像、免疫组化染色分离颜色、过滤区域最大值
【PHP】PHP接口继承及接口多继承原理与实现方法