一支持跨域处理。
前端代码略(vue 进行axios 请求。)
未设置允许跨域名
进行如下处理。
//1 program.cs
builder.Services.AddCors(c=>c.AddPolicy("any", p => p.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin()));
...
app.UseCors();
//2 控制器代码 。
using Microsoft.AspNetCore.Cors;
namespace demo.Controllers;
[EnableCors("any")]
二 关于传参的几个细节。
2.1
[HttpGet]
public string Get2(int id ,string name)
{
return "hello world " + id + name;
}
int 未填时,默认为0, string 未填则400 , 如果希望可传可不传,参数改为 string? name.
2.2 当post json内容时。
//http://localhost:5244/Test/Post?id=222&name=33333
axios.post("http://localhost:5244/Test/Post", {id:666, name:"xxx"}).then((res)=>{
userName.value = res.data;
//console.log(res.data);
})
//控制器中。使用model 来接。
[HttpPost]
public string Post( demo.Models.TestPostModel model )
{
return "from model" + model.id + model.name ;
}
//用 model 代码来接。
namespace demo.Models;
public class TestPostModel {
public int id {set;get;}
public string name {get;set;}
}
为什么 Post( demo.Models.TestPostModel model ) 就可以接到。 [ApiController] 参与完成了参数推断。
2.3 数据验证支持
//model 代码 。
using System.ComponentModel.DataAnnotations;
[MaxLength(6)]
public string name {get;set;}
//具体玩法,找手册。
3 restFul 风格。iActionResult ,ActionResult
很垃圾的一套风格,看起来很标准,其实没啥屁用,而且让本来很极简单的事情,硬生生的多出几步流程,让业务麻烦 ,直接响应个json 应该更香。(仅个人观点)
4 minimal Apis
app.MapGet("/", () => "hello world");