Skip to content

Instantly share code, notes, and snippets.

@crosstyan
Last active July 2, 2020 07:48
Show Gist options
  • Save crosstyan/973e4843067ab09b04db1881379d8654 to your computer and use it in GitHub Desktop.
Save crosstyan/973e4843067ab09b04db1881379d8654 to your computer and use it in GitHub Desktop.
A basic C sharp web app example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace MyApp.Controllers {
[ApiController]
//path: "/hello"
//the same as the Controller name
//If you mistype the "HelloControer" (it won't be treated as a controller)
[Route("[controller]")]
public class HelloController : ControllerBase {
//Can't access in "/hello/nickname"
//[HttpGet("{nickname}/{another}")]
//[HttpGet("{nickname}")]
[HttpGet]
// https://docs.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-3.1
public IActionResult WhaterveYouWannaCallIt([FromQuery]string name, [FromRoute]string nickname,[FromRoute] string another) {
var hw = $"Hello {nickname}";
//Http State Code
return Ok(hw);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
//它只做一件事, 就是创建一个HostBuilder, 从Startup.cs调取配置文件, 总之, 不用关心它(大概)
//命名空间就是你的项目名称, 自动创建的, 其实你想叫啥都可以啦.
namespace MyApp {
public class Program {
//你的Main函数
public static void Main(string[] args) {
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => {
webBuilder.UseStartup<Startup>();
});
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyApp.Models;
namespace MyApp.ControllersOrSomething {
//用方括号括起来的大概是修饰器(不对叫做Attributes)
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/
[ApiController]
//Route, 括号里面的是其Path, [controller]就是用其**类**名称替代
//和[Route("/rabbit")]是等效的
[Route("[controller]")]
//别拼错Controller了, 拼成别的是不会认的
public class RabbitController : ControllerBase {
//大家很熟悉的Get方法
[HttpGet]
//一个实现ActionResult的方法. Index为方法名(叫啥都行)
public IActionResult Index() {
//可以直接读Req和Res
var req = Request;
var res = Response;
res.StatusCode = 404;
res.ContentType = "application/json";
//匿名对象
var anonymous = new { Code = 404, Description = "I'm a rabbit, but I'm lost" };
//dynamic类型
// https://docs.microsoft.com/zh-tw/dotnet/csharp/programming-guide/types/using-type-dynamic
var json = JsonSerializer.Serialize<dynamic>(anonymous);
res.WriteAsync(json);
return NotFound();//这里的Return好像没啥卵用, 因为直接写到了Res中.
//这也不是很MVC, 顺便一提
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
//用户自定义的Models, 在后文会用到的
using MyApp.Models;
namespace MyApp {
// https://docs.microsoft.com/zh-tw/aspnet/core/fundamentals/?view=aspnetcore-3.1&tabs=windows
public class Startup {
//看不懂, 大概是做一些不太明白的Configuration
//Startup 的 Constructor
public Startup(IConfiguration configuration) {
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
//这个方法是用来向Container中添加Services的
//重点来了, 这个地方用于添加各种Services
//用于Dependency Injection
public void ConfigureServices(IServiceCollection services) {
//Bind all the controller
//I mean all the controller
//所有的API Controller, 类名后边带Controller的都会被绑定上
services.AddControllers();
//各种服务, 整不明白, 添加服务之后还得到下面加路由
//services.AddRazorPages();
//services.AddSignalRCore();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
//配置一些HTTP相关的玩意, 也是重头戏.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
if (env.IsDevelopment()) {
//如果在开发环境那就显示专供开发者的ExceptionPage
//好像是在launchSettings里边设置的?
app.UseDeveloperExceptionPage();
}
//和HTTPS有关的玩意
// https://docs.microsoft.com/en-us/aspnet/core/security/enforcing-ssl?view=aspnetcore-3.1&tabs=visual-studio
app.UseHttpsRedirection();
//[ASP.NET Core 3.0 中 app.UseRouting 与 app.UseEndpoints 的区别是什么](https://q.cnblogs.com/q/115276/)
app.UseRouting();
//用于验证的中间件
//app.UseAuthorization was added to the templates to show the order authorization middleware must be added.
//If the app doesn't use authorization, you can safely remove the call to app.UseAuthorization.
app.UseAuthorization();
app.UseEndpoints(endpoints => {
//Add router for all the controller
//和上边的services.AddControllers()一样, Map所有的Controllers的endpoints
endpoints.MapControllers();
//各种各样的服务
//endpoints.MapRazorPages();
//endpoints.MapBlazorHub();
//这就有点意思了, 是不是想起了
//app.get("/anotherhello",(req,res)=>{})
//和各种类sinatra框架的写法很像了
//但是C#并不鼓励你这么写, 这不MVC
endpoints.MapGet("/anotherhello", (content) => {
var req = content.Request;
var res = content.Response;
var path = req.Path;
var query = req.QueryString;
var toDo = new ToDoItem { Id = 12345, Name = "hello", IsComplete = false }.ToString();
return content.Response.WriteAsync($"{toDo} from {path}, {query}");
});
});
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
namespace MyApp.Models {
public class ToDoItem {
//如果用VS的话创建类属性可以直接用
//prop 然后点两下Tap完事
public long Id { get; set; }
public string Name { get; set; }
public bool IsComplete { get; set; }
//覆写了ToString()方法, 使其JSON化
public override string ToString() {
//可选的类型声明
//return JsonSerializer.Serialize(this);
//我猜用尖括号括起来的是输入值的类, 但是我没有证据.
//Serialize 相当于json.stringify或者json.Marshal
return JsonSerializer.Serialize<ToDoItem>(this);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment