【Asp.Net.Core】【Controller】

73 阅读1分钟

Introduction to Controllers

与JAVA中概念相同,这里不做过多解释啦!!! image.png

创建 controller

  1. 创建Controllers 文件夹以及Controllerimage.png

  2. 创建类

using Microsoft.AspNetCore.Mvc;

namespace ControllerExample.Controllers
{
   public class HomeController
   {
        [Route("sayhello")]   //路径
        public string method1()
        {
            return "hello from method1\n";
        }
   }
}
  1. 使用Controller
using ControllerExample.Controllers;

var builder = WebApplication.CreateBuilder(args);

//builder.Services.AddTransient<HomeController>(); //只添加一个controller
builder.Services.AddControllers(); //add all the controller classes
// as services

var app = builder.Build();
/*app.UseRouting();    //enable Routing
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers(); //enable routing for each method
});*/

app.MapControllers();  //automatically enable routing and endpoints

app.Run();

多个映射路径怎么办?——直接添加

using Microsoft.AspNetCore.Mvc;

namespace ControllerExample.Controllers
{
   [Controller]
   public class HomeController
   {
        [Route("about")]   //路径
        public string About()
        {
            return "hello from about\n";
        }


        [Route("contact-us/{mobile:regex(^\\d{{11}}$)}")]   //路径
        public string Contact()
        {
            return "hello from contact-us\n";
        }

        [Route("home")]   //路径
        [Route("/")]   //路径
        public string Index()
        {
            return "hello from Index\n";
        }
    }
}

小结: image.png

image.png

响应结果形式

ContentResult

image.png

代码示例:

public class HomeController: Controller
{
     [Route("about")]   //路径
     public ContentResult About()
     {
        /* return new ContentResult()
         {
             Content =
             "hello from about\n",
             ContentType = "text/plain"
         };*/

         //return Content("hello from about\n", "text/plain");
         return Content("<h1>welcome<h1> \n " +
             "<h2>Hello from Index<h2>", "text/html");  //需要继承Controller
     }
}

JsonResult

image.png

  1. 创建实体
namespace ControllerExample.Models
{
    public class Person
    {
        public Guid Id { get; set; }
        public string? FirstName { get; set; }
        public string? LastName { get; set; }
        public int Age { get; set; }
    }
}

2.返回Json对象

[Route("person")]   //路径
public JsonResult Person()
{
    Person person = new Person()
    {
        Id = Guid.NewGuid(),
        FirstName = "James",
        LastName = "Smith",
        Age = 26
    };
    //return new JsonResult(person);
    return Json(person);     //继承Controller
}

File Results

image.png

FileResult可以分为3类:

image.png

主要区别如下:

image.png

image.png

使用如下:

[Route("file-download")]    //在wwwroot中用 VirtualFileResult
public VirtualFileResult FileDownload()
{
   // return new VirtualFileResult("/kaiti.pdf", "application/pdf");
    return File("/kaiti.pdf", "application/pdf");
}

[Route("file-download2")]    //在其他地方文件使用 PhysicalFileResult
public PhysicalFileResult FileDownload2()
{
    //return new PhysicalFileResult(@"C:\Users\17338\Desktop\0309.pdf", "application/pdf");
    return PhysicalFile(@"C:\Users\17338\Desktop\0309.pdf", "application/pdf");
}

[Route("file-download3")]    //读取的是字节时,使用FileContentResult
public FileContentResult FileDownload3()
{
    
    byte[] bytes = System.IO.File.ReadAllBytes(@"C:\Users\17338\Desktop\0309.pdf");
   // return new FileContentResult(bytes, "application/pdf");
    return File(bytes, "application/pdf");
}

IActionResult

可以接收任意的返回值。

image.png

Status Code Results

image.png

image.png

示例:

//program.cs下的代码

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();

app.UseStaticFiles();
app.UseRouting();
app.MapControllers();

app.Run();
//HomeController 下的代码
using Microsoft.AspNetCore.Mvc;

namespace IActionExample.Controllers
{
    public class HomeController : Controller
    {
        [Route("Book")]
        public IActionResult Index()
        {
            //Book id should be applied
            if(!Request.Query.ContainsKey("bookid"))
            {
               // Response.StatusCode = 400;
                //return Content("Book id is not supplied");
                return BadRequest("Book id is not supplied")
            }
            //Book id can't be empty
            if (string.IsNullOrEmpty(Convert.ToString(Request.Query["bookid"])))
            {
                //Response.StatusCode = 400;
                //return Content("Book id can't be null or empty");
                return BadRequest("Book id can't be null or empty");
            }
            //Book id should be between 1 and 1000
            int bookId = Convert.ToInt32(Request.Query["bookid"]);
            if(bookId <1 || bookId > 1000)
            {
               // Response.StatusCode = 400;
              //  return Content("Book id should be between 1 and 1000");
              //  return new BadRequestResult();
                return BadRequest("Book id should be between 1 and 1000");
            }
            if (Convert.ToBoolean(Request.Query["isloggedin"]) == false)
            {
                //Response.StatusCode = 401;
                //return Content("You are not logged in.");
                return Unauthorized("You are not logged in.");

                // return StatusCode(401);
            }
            
            return File("/kaiti.pdf", "application/pdf");
        }
    }
}

Redirect Results

image.png

  1. RedirectToActionResult——需要ActionNameControllerName,RouteValues(常用)。
  2. LocalRedirectResult——只需要URL
  3. Redirect——跨域请求
  4. 如果方法后边没有加Permanent,表明临时重定向,状态码为301,浏览器URL会变化;
  5. 如果方法后边加Permanent,表明永久重定向,状态码为302
using Microsoft.AspNetCore.Mvc;

namespace IActionExample.Controllers
{
    public class HomeController : Controller
    {
        [Route("bookstore")]
        public IActionResult Index()
        {
            //Book id should be applied
            if(!Request.Query.ContainsKey("bookid"))
            {
                // Response.StatusCode = 400;
                //return Content("Book id is not supplied");
                return BadRequest("Book id is not supplied");
            }
            //Book id can't be empty
            if (string.IsNullOrEmpty(Convert.ToString(Request.Query["bookid"])))
            {
                //Response.StatusCode = 400;
                //return Content("Book id can't be null or empty");
                return BadRequest("Book id can't be null or empty");
            }
            //Book id should be between 1 and 1000
            int bookId = Convert.ToInt32(Request.Query["bookid"]);
            if(bookId <1 || bookId > 1000)
            {
               // Response.StatusCode = 400;
              //  return Content("Book id should be between 1 and 1000");
              //  return new BadRequestResult();
                return BadRequest("Book id should be between 1 and 1000");
            }
            if (Convert.ToBoolean(Request.Query["isloggedin"]) == false)
            {
                //Response.StatusCode = 401;
                //return Content("You are not logged in.");
                return Unauthorized("You are not logged in.");

                // return StatusCode(401);
            }

            //return new RedirectToActionResult("Books", "Store", new { }); //302-Found
                                                                          // return File("/kaiti.pdf", "application/pdf");
            //return new RedirectToActionResult("Books", "Store", new { },true); //301-Move Permanently 

           //return RedirectToAction("Books", "Store", new { id = bookId});

            // return RedirectToActionPermanent("Books", "Store", new { id = bookId });   更常用

            return new LocalRedirectResult($"store/books/{bookId}");  
            return LocalRedirect($"store/books/{bookId}");          //302 - Found


            return LocalRedirectPermanent($"store/books/{bookId}"); //301 - Move Permanently

        }
using Microsoft.AspNetCore.Mvc;

namespace IActionExample.Controllers
{
    public class StoreController : Controller
    {
        [Route("store/books/{id}")]
        public IActionResult Books()
        {
            int id = Convert.ToInt32(Request.RouteValues["id"]);
            return Content($"<h1>Book Store {id}<h1>","text/html");
        }
    }
}