目录
一、创建项目
新建一个 ASP.NET Web Core API 项目
二、启动项目
创建成功后,默认会有一个天气预报的控制器 WeatherForecastController.cs
启动调试后,会自动弹出这个界面,但这个不是我们想要的
直接在浏览器输入链接:https://localhost:44363/WeatherForecast
数据是 WeatherForecastController.cs 中的 Get方法 返回的:
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
到此为止,一个简单的接口就写好了,但此时其他的电脑访问会访问不到这个接口,下面就解决这个问题
三、开放其他电脑访问权限
1.launchSettings.json
将 "applicationUrl" 改为 "http://0.0.0.0:5000",完整代码如下:
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:63035",
"sslPort": 44395
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"WebApplication2": {
"commandName": "Project",
"dotnetRunMessages": "true",
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://0.0.0.0:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
2.Program.cs
在 Program.cs 中加入下面代码:
webBuilder.ConfigureKestrel(options => options.ListenAnyIP(5000));
完整代码如下:
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication2
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.ConfigureKestrel(options => options.ListenAnyIP(5000));
});
}
}
四、调用接口
生成程序后,在debug目录下,启动程序
启动程序
用软件 Postman 调用接口,可以看到调用成功了
五、添加其他API
想加其他的接口,在Controllers文件夹下加就行了,控制器名字后面加个Controller
例子:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
namespace WebApplication2.Controllers
{
[ApiController]
[Route("[controller]")]
public class MatchFingerprintController : ControllerBase
{
[HttpGet]
public string Get()
{
return "指纹匹配";
}
[HttpPost]
public string Post()
{
return "what fuck shit";
}
}
}
使用软件 Postman 调用 http://192.168.124.78:5000/MatchFingerprint 接口
这样就收到来自服务器的回复了
end