.net core 應用Nancy快速實現輕量級webapi


目前大量數據接口均采用API的方式為各類應用提供數據服務。Nancy是.net下實現webapi的一個輕量級的框架,可以快速搭建一個api服務環境,是一種快速建立api服務的不錯選擇。

本文記錄.net core環境下利用Nancy快速搭建webapi的全過程。

Ⅰ.開發環境

跨平台的: .net core 2.1

宇宙級ide:vs2017

Ⅱ.代碼實現

1.新建應用框架

 

 

2.下載安裝Nancy類庫,由於需要支持.netcore環境,則需要安裝Nancy2.0版本。執行下面的包安裝命令。

 所需要包的目錄結構如下:

 

3.實現.netcore支持Nancy,修改Startup.cs文件中Configure的內容

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Nancy.Owin;

namespace Nancy.Web
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseOwin(x => x.UseNancy());

            //app.Run(async (context) =>
            //{
            //    await context.Response.WriteAsync("Hello World!");
            //});
        }
    }
}

3.實現路由訪問,新建HomeModule.cs類,繼承NancyModule,開始寫Nancy格式的路由。路由寫法參見文檔

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Nancy;
using Nancy.ModelBinding;

namespace Nancy.Web
{
    public class HomeModule:NancyModule
    {
        public HomeModule()
        {
            Get("/", r => "Hello,Nancy,i am running on ASP.NET Core");
            Get("/{name}", r => "你好:" + r.name);

Post("/loadstr", r => { var strRecive = this.Bind<InputStr>(); return strRecive.inputstr; }); } } }

4.解決跨域訪問,新建Bootstrapper.cs類,該類為Nancy特有配置類,重寫ApplicationStartup方法。

using Nancy.Bootstrapper;
using Nancy.TinyIoc;

namespace Nancy.Web
{
    public class Bootstrapper: DefaultNancyBootstrapper
    {
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            //CORS Enable  解決跨域問題           
            pipelines.AfterRequest.AddItemToEndOfPipeline((ctx) =>
            {

                ctx.Response.WithHeader("Access-Control-Allow-Origin", "*")  // * 允許跨域問題的網站  *號代表面向所有網站  也可指定網站,如 http://localhost:8080
                            .WithHeader("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE,OPTION")
                            .WithHeader("Access-Control-Allow-Headers", "Accept, Origin, Content-type");

            });

        }
    }
}

5.新建InputStr.cs類,用於測試post提交數據

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Nancy.Web
{
    public class InputStr
    {
        public string inputstr { get; set; }//定義輸入字符串
    }
}

 

整體文件目錄如下:

 

測試一下,看看運行效果

 

 

Ⅲ.應用部署

1.發布應用

 

 

2.部署至IIS,將上面發布至publish文件夾的文件拷貝到IIS服務器上

 

編輯應用程序池,因為是.net core項目,所以.net framework版本設置為“無托管代碼”

 

3.利用PostMan進行程序測試

GET方式

POST方式

 

好啦,從搭建、測試到部署完成了一個輕量級的webapi。下一步可以根據具體需求進行擴展,愉快的開發接口了。

下載源碼戳這里


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM