您的位置:首页 > 其它

基于 WebAPI 的 API 实现

2016-07-28 16:29 369 查看
本文基于

WebAPI

OData (微软发起的一个格式标准,其中一个比较有意思的是可以直接在 Excel 中填入 API 就可以展示了)

Swashbuckle.OData(把 API 生成一个测试页面)

项目结构

public class EfContext : DbContext
{
/// <summary>
/// Users
/// </summary>
public DbSet<UserModel> Users { get; set; }

/// <summary>
/// EfContext ctor
/// </summary>
public EfContext()
: base("name=EfContext")
{
}

/// <summary>
/// This method is called when the model for a derived context has been initialized, but
///             before the model has been locked down and used to initialize the context.  The default
///             implementation of this method does nothing, but it can be overridden in a derived class
///             such that the model can be further configured before it is locked down.
/// </summary>
/// <remarks>
/// Typically, this method is called only once when the first instance of a derived context
///             is created.  The model for that context is then cached and is for all further instances of
///             the context in the app domain.  This caching can be disabled by setting the ModelCaching
///             property on the given ModelBuidler, but note that this can seriously degrade performance.
///             More control over caching is provided through use of the DbModelBuilder and DbContextFactory
///             classes directly.
/// </remarks>
/// <param name="modelBuilder">The builder that defines the model for the context being created. </param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);

modelBuilder.Configurations.Add(new UserModelMap());
}
}


View Code
Tips:

53515 是项目设置 Web 选项里的端口号,具体请查询真实的端口号

勾选项目设置 Build 选项里的XML documentation file,因为 Swagger 会用 xml 里的注释作为说明,请把代码中的 /// 注释补全,这样才能生成说明



运行结果

由于测试直接返回的固定数据,所以,当运行后就可以通过 API 得到结果了,并且可以通过 Swagger 测试页面看到 API 的信息,并可以测试。

此例中的 API 为
http://localhost:53515/Users?$orderby=Id desc (请求的 API)
http://localhost:53515/swagger/ui/index#/ (Swagger 生成的测试页面)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: