创建 web API程序及在IIS上部署
1.在 Visual Studio 中创建一个新的 ASP.NET Core Web 应用程序2.选择API3.创建Models文件夹并新建类User public class User { public string m_UserName { get; set; } public string m_UserPassword { g...
1.在 Visual Studio 中创建一个新的 ASP.NET Core Web 应用程序
2.选择API
3.创建Models文件夹并新建类User
public class User
{
public string m_UserName { get; set; }
public string m_UserPassword { get; set; }
public string m_UserPreviliage { get; set; }
}
4.新建Config类(存储全局变量)
类内容如下:
public class Config
{
public static string dbconn;
}
5.在配置文件appsettings.json中加入数据库连接,添加后内容如下:
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"dbconn": "Server=192.168.1.123;Port=3306;Database=dorremotedata;User ID=root;password=xlf123456;SslMode=None"
}
6.在NuGet里引用MySql.Data库 并新建DataContext类
类内容如下:
public class DataContext : DbContext
{
public DbSet<User> t_user { get; set; } //t_user 为数据库中表名
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseMySQL(Config.dbconn);
}
7.新建Interfaces文件夹并创建接口IUserFuncs
public interface IUserFuncs
{
bool IsUserExist(string name,string password);
}
8.新建Server文件夹并创建类UserFuncs
public class UserFuncs: DataContext
{
public static bool Get(string name, string password)
{
try
{
using (var context = new DataContext())
{
var query = from c in context.t_user where c.UserName == name & c.UserPassword == password select c;
if (query != null)
{
int a = query.Count();
if (a >= 1)
return true;
else
return false;
}
}
}
catch (Exception ex)
{
return false;
}
return false;
}
}
9.新建UserController
内容如下:
[Route("api/[controller]")]
public class UserController : Controller
{
// GET api/user/5
[HttpPost]
public IActionResult Get([FromBody] User user)
{
return Ok(UserFuncs.Get(user.UserName, user.UserPassword));
}
}
10.加载配置文件
在Program类中main方法中添加代码:
private static IConfigurationRoot Configuration { get; set; }
public static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
Config.dbconn = Configuration.GetValue<string>("dbconn");
CreateWebHostBuilder(args).Build().Run();
}
编译后就可以了!
10.部署
11.可能异常
12.调试工具
Postman
更多推荐
所有评论(0)