使用控制台程序搭建WebApi
原文参考:
ASP.NET Web Api 2.2: Create a Self-Hosted OWIN-Based Web Api from Scratch
新建控制台程序,引入Owin包
PM> Install-Package Microsoft.AspNet.WebApi.OwinSelfHost -Pre
添加Startup类
public class Startup
{
public void Configuration(IAppBuilder app)
{
var webApiConfiguration = ConfigureWebApi();
// Use the extension method provided by the WebApi.Owin library:
app.UseWebApi(webApiConfiguration);
}
private HttpConfiguration ConfigureWebApi()
{
var config = new HttpConfiguration();
config.Routes.MapHttpRoute(
"DefaultApi",
"api/{controller}/{id}",
new { id = RouteParameter.Optional });
return config;
}
}
添加Models、Controllers文件夹,添加Company、CompaniesController
public class Company
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
public class CompaniesController : ApiController
{
ApplicationDbContext _Db = new ApplicationDbContext();
public IEnumerable<Company> Get()
{
return _Db.Companies;
}
public async Task<Company> Get(int id)
{
var company = await _Db.Companies.FirstOrDefaultAsync(c => c.Id == id);
if (company == null)
{
throw new HttpResponseException(
System.Net.HttpStatusCode.NotFound);
}
return company;
}
public async Task<IHttpActionResult> Post(Company company)
{
if (company == null)
{
return BadRequest("Argument Null");
}
var companyExists = await _Db.Companies.AnyAsync(c => c.Id == company.Id);
if (companyExists)
{
return BadRequest("Exists");
}
_Db.Companies.Add(company);
await _Db.SaveChangesAsync();
return Ok();
}
public async Task<IHttpActionResult> Put(Company company)
{
if (company == null)
{
return BadRequest("Argument Null");
}
var existing = await _Db.Companies.FirstOrDefaultAsync(c => c.Id == company.Id);
if (existing == null)
{
return NotFound();
}
existing.Name = company.Name;
await _Db.SaveChangesAsync();
return Ok();
}
public async Task<IHttpActionResult> Delete(int id)
{
var company = await _Db.Companies.FirstOrDefaultAsync(c => c.Id == id);
if (company == null)
{
return NotFound();
}
_Db.Companies.Remove(company);
await _Db.SaveChangesAsync();
return Ok();
}
}
添加EntityFramework包,添加ApplicationDbContext
namespace ConsoleWebApi.Models
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext() : base("MyDatabase")
{
}
public IDbSet<Company> Companies { get; set; }
}
public class ApplicationDbInitializer : DropCreateDatabaseAlways<ApplicationDbContext>
{
protected override void Seed(ApplicationDbContext context)
{
base.Seed(context);
context.Companies.Add(new Company { Name = "Microsoft" });
context.Companies.Add(new Company { Name = "Google" });
context.Companies.Add(new Company { Name = "Apple" });
}
}
}
App.Config中添加连接字符串
<connectionStrings>
<add name="MyDatabase" connectionString="Data Source=.;Initial Catalog=Test;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" providerName="System.Data.SqlClient"/>
</connectionStrings>
入口Main中添加代码
static void Main(string[] args)
{
Console.WriteLine("Initializing and seeding database...");
Database.SetInitializer(new ApplicationDbInitializer());
var db = new ApplicationDbContext();
int count = db.Companies.Count();
Console.WriteLine("Initializing and seeding database with {0} company records...", count);
string baseUri = "http://localhost:8080";
Console.WriteLine("Starting web Server...");
WebApp.Start<Startup>(baseUri);
Console.WriteLine("Server running at {0} - press Enter to quit. ", baseUri);
Console.ReadLine();
}
启动程序,打开http://localhost:8080/api/companies/1
即可看到结果。
使用控制台程序搭建WebApi的更多相关文章
- 使用控制台程序搭建OAuth授权服务器
参考地址:ASP.NET Web Api: Understanding OWIN/Katana Authentication/Authorization Part I: Concepts 先上一张OA ...
- WebAPI搭建(一)如何在Webforms 下 搭建WebAPI
公司的很多项目前期一直是用的WebForms.但是因为业务的发展,公司要在原有的项目上接入移动端,webservice有点老旧了,现在比较流行RESTFul,于是乎就想到了WebAPI. 一.如果是新 ...
- 从零开始搭建WebAPI Core_SqlSugar管理系统(一) 项目环境需求以及项目搭建
从零开始搭建WebAPI Core_SqlSugar管理系统(一) 项目环境需求以及项目搭建 环境需求 想要使用.NET Core,首先你的Visual Studio(以下简称vs)升级到较高的版本, ...
- 如何使用程序调用webApi接口
如何使用程序调用webApi接口 在C#中,传统调用HTTP接口一般有两种办法: WebRequest/WebResponse组合的方法调用 WebClient类进行调用. 第一种方法抽象程度较低,使 ...
- 从零开始搭建WebAPI Core_SqlSugar管理系统 (持续更新中......)
从零开始搭建WebAPI Core_SqlSugar管理系统 前言 本系列皆在从零开始逐步搭建,后台管理系统服务端部分,后续还会推出前端部分. 这次的目的是搭出一个功能完善的 本次系列技术栈以下几个部 ...
- 微信小程序搭建mpvue+vant+flyio
导语 上一篇文章微信小程序搭建mpvue+vant已经介绍了如何搭起mpvue项目及引入vant,本篇文章继续在它的基础上,引入flyio,并做一些封装,目的是为了在小程序发起请求. 这时读者会有些疑 ...
- 微信小程序搭建mpvue+vant
第一步:查看是否已经装了node.js $ node -v $ npm -v 正确姿势 没有装的话前往Node.js官网安装 第二步:安装cnpm $ npm install -g cnpm -- ...
- 开箱即用Bumblebee独立部署搭建webapi网关详解
在之前的章节里都是讲述如何在程序中使用Bumblebee来构建一个Webapi网关:但这样显然有些麻烦,毕竟很多时候可能只需要一个简单负载处理,还需要写个程序针对服务进行编写代码或配置的确是比较麻烦的 ...
- webapi框架搭建-webapi异常处理
webapi框架搭建系列博客 前言 上一篇我们已经完成了项目的日志管理,在项目开发中日志会经常记录程序中的异常,供后续问题排查使用.本篇讲如何在webapi里加入异常处理机制. 目的和原则 1.程序任 ...
随机推荐
- issubclass ,isinstance,反射
issubclass() 函数 issubclass() 方法用于判断参数 class 是否是类型参数 classinfo 的子类. 语法 以下是 issubclass() 方法的语法: issubc ...
- Android多点触控手势基础
处理多点触控手势 多点触控就是同时把一根以上的手指放在屏幕上. 再继续往下以前需要补充一些名词: 触控手势:就是把一根或者几根手指放在屏幕上做各种动作,其中包括保留一根手指的前提下,拿起或者放下其余的 ...
- Warning the user/local/mysql/data directory is not owned by the mysql user
sudo chown -RL root:mysql /usr/local/mysql sudo chown -RL mysql:mysql /usr/local/mysql/data sudo /us ...
- python-Django-01基础配置
参考资料地址 http://www.ziqiangxuetang.com/django/django-install.html 官方文档 一: 1先下载Django源码包,下载地址https://ww ...
- io类型
非阻塞io from socket import * import time s=socket(AF_INET,SOCK_STREAM) s.bind(('127.0.0.1',8080)) s.li ...
- QT7有用的尝试总结(1)
1,系统配置 1. 把系统相关的一些目录配置 写到qt.conf文件里,详细情况情参考QSettings里的qt.conf部分 You can use the qt.conf file to over ...
- hdu 4135 [a,b]中n互质数个数+容斥
http://acm.hdu.edu.cn/showproblem.php?pid=4135 给定一个数n,求某个区间[a,b]内有多少数与这个数互质. 对于一个给定的区间,我们如果能够求出这个区间内 ...
- LCA的 RMQ解法模版
struct Edge{ int from, to, nex; }edge[N<<1]; int head[N], edgenum; void addedge(int u, int v){ ...
- django后台admin管理布局
在model模块里设置 class pc_info(models.Model): ip = models.CharField(max_length=64) sn = models.CharField( ...
- Python自动化开发 - 内置函数总结
Python解释器提供了很多内置函数 参考链接:https://docs.python.org/3.6/library/functions.html 一.数学相关 1.绝对值:abs(-1) 2.最大 ...