Giter Site home page Giter Site logo

webapisample's Introduction

WebApi教程

使用Api基础模板

  • 1.新建带有Enitity Framework增删改查模板的控制器

  • 2.选择控制器强类型和数据库上下文

  • 3.模板Api代码生成

Jsonp跨域访问

  • 1.自定义jsonp返回:
    public HttpResponseMessage GetBooks(string callback)
    {
        string func = $"{callback}({JsonConvert.SerializeObject(db.Books)})";
        return new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StringContent(func, Encoding.UTF8, "text/javascript")
        };
    } 
  • 2.添加jsonp的格式化器(全局支持jsonp调用):
    • 安装依赖:Install-Package WebApiContrib.Formatting.Jsonp
    • 引入配置:
    using WebApiContrib.Formatting.Jsonp;

    public static void Register(HttpConfiguration config)
    {
        // Web API 配置和服务

        // Web API 路由
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        // 添加jsonp的格式化器
        config.AddJsonpFormatter();
    }

CORS跨域访问

  • 安装依赖:Install-Package Microsoft.AspNet.WebApi.Cors
  • 引入配置:
    public static void Register(HttpConfiguration config)
    {
        // Web API 配置和服务

        // Web API 路由
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        // 添加cors跨域配置
        config.EnableCors();
    }
  • 使用配置:
    // 指定api接口请求的白名单:只有来自 http://localhost:53462 的请求方可访问
    [EnableCors(origins: "http://localhost:53462",headers:"*",methods:"*")]
    // GET: api/Book
    public IQueryable<Book> GetBooks()
    {
        return db.Books;
    }

Swagger UI 的使用

  • 安装依赖:Install-Package Swashbuckle
  • 生成项目xml文档:
  • 指定xml路径:
    protected static string GetXmlCommentsPath()
    {
        var baseDir = AppDomain.CurrentDomain.BaseDirectory;
        var fileName = Assembly.GetExecutingAssembly().GetName().Name + ".xml";
        var file = Path.Combine(baseDir, "bin", fileName);
        return file;
    }

自主宿主HttpSelfHost

  • 安装依赖:Install-Package Microsoft.AspNet.WebApi.SelfHost
    static void Main(string[] args)
    {
        //加载插件
        var files = Directory.GetFiles(Path.Combine(Environment.CurrentDirectory, "plugins"))
            .Where(f=>f.ToLower().EndsWith(".dll")).ToList();
        files.ForEach(file => Assembly.LoadFile(file));

        //配置主机
        var address = "http://127.0.0.1:8081";
        var config = new HttpSelfHostConfiguration(address);
        //配置路由
        config.Routes.MapHttpRoute("Default", "api/{version}/{controller}/{id}", new { version = RouteParameter.Optional, id = RouteParameter.Optional });

        // 自定义api根据需求返回格式
        config.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("format", "json", "application/json"));
        config.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("format", "xml", "application/xml"));

        //监听HTTP
        var server = new HttpSelfHostServer(config);
        //开启来自客户端的请求
        server.OpenAsync().Wait();
        Console.WriteLine($"服务已经启动 {address} 请按任意键键退出");
        Console.ReadKey();
    }

文件上传与下载

结果展示

扩充:

  • 自定义根据参数返回格式:
    public static void Register(HttpConfiguration config)
    {
        // 自定义api根据需求返回格式
        config.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("format", "json", "application/json"));
        config.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("format", "xml", "application/xml"));

        // Web API 配置和服务

        // Web API 路由
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        // 添加jsonp的格式化器
        config.AddJsonpFormatter();

        // 添加cors跨域配置
        config.EnableCors();
    }

    // 具体请求使用案例:
    /api/book?format=json
    /api/book?format=xml

webapisample's People

Contributors

run2948 avatar

Stargazers

yuanchanglong avatar Jinghao Hu avatar  avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.