zoukankan      html  css  js  c++  java
  • 新建一个self hosted Owin+ SignalR Project(1)

            OWIN是Open Web Server Interface for .Net 的首字母缩写,他的定义如下:

            OWIN在.NET Web Server 与Web Application之间定义了一套标准接口,OWIN的目标是用于解耦Web Server和Web Application.基于此标准,鼓励开发者开发简单,灵活的模块,从而推进.Net Web Development开源生态系统的发展.之前.net开发的所有webSite和Web Application不得不和IIS绑定到一起部署,对于部署,相当笨重.而OWIN正好是为了解决这个问题!

             1.新建一个Console项目

             2.添加Owin self host 引用,打开NuGet 程序包管理平台,输入如下代码:

    >install-package Microsoft.Aspnet.WebApi.OwinSelfHost

             3.新建一个名字为StartUp.cs的类,添加如下代码:

    using Owin;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web.Http;
    
    namespace TestProgram
    {
       public class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                //模仿站点配置
                HttpConfiguration config = new HttpConfiguration();
                //添加站点路由
                config.Routes.MapHttpRoute(
                    name: "DefaultApi", 
                    routeTemplate: "api/{controller}/{action}/{id}", //这里为了类MVC特别加入了{action}
                    defaults: new { id = RouteParameter.Optional });
                app.UseWebApi(config);  
            }
        }
    }

             4.添加Controller,新建文件夹Controller,添加IndexController.cs,添加如下代码:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web.Http;
    
    namespace TestProgram.Controller
    {
      public  class IndexController:ApiController
        {
            public string Get(string name)
            {
                return name;
            }
         }
    }

             5.将Owin站点启动,修改Program.cs,如下:

    using Microsoft.Owin.Hosting;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace TestProgram
    {
        class Program
        {
            static void Main(string[] args)
            {
                //此入口是Owin站点的宿主
                string baseAddress = "http://localhost:9009/";//站点启动地址
                using (WebApp.Start<Startup>(baseAddress))
                {
                    HttpClient client = new HttpClient();
                    //var response = client.GetAsync(baseAddress + "api/index").Result;
                    //Console.WriteLine(response);
                    //Console.WriteLine(response.Content.ReadAsStreamAsync().Result);
                    Console.ReadLine();//不让宿主程序结束
                }
            }
        }
    }

             6.运行程序,打开浏览器输入 http://localhost:9009/index/index?name="RemiHoston"

             

               由于没有设置返回的数据类型,所以默认返回XMl格式,但是,只是返回字符串并不能满足要求;但是Owin self hosted 程序宿主于Console没有提供文件下载访问,所以我们要自己提供接口支持文件访问

               7.添加静态文件访问的接口

                 修改IndexController.cs添加如下两个方法:

     [HttpGet]
            public HttpResponseMessage Index()
            {
                //构造文件路径,代码重构的时候可以把这一块代码封装成公用方法
                var currentRunPath = AppDomain.CurrentDomain.BaseDirectory;
                var substringBin = currentRunPath.IndexOf("bin");
                //返回Index.html文件
                var path = currentRunPath.Substring(0, substringBin) + "Index.html";
                var httpResponseMessage = new HttpResponseMessage();
                httpResponseMessage.Content = new StringContent(File.ReadAllText(path), Encoding.UTF8); 
                httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
                //把文件内容读出来,以HttpResponseMessage的形式返回客户端
                return httpResponseMessage;
            }
            /// <summary>
            /// 获取静态文件,比如css,javascript
            /// </summary>
            /// <param name="fileName"></param>
            /// <returns></returns>
            [HttpGet] 
            public HttpResponseMessage GetResource(string fileName)
            {
                //构造文件路径,代码重构的时候可以把这一块代码封装成公用方法
                var currentRunPath = AppDomain.CurrentDomain.BaseDirectory;
                var substringBin = currentRunPath.IndexOf("bin");
                var path = currentRunPath.Substring(0, substringBin) + fileName;
              
                var httpResponseMessage = new HttpResponseMessage();
                if (!File.Exists(path))
                {
                    httpResponseMessage.StatusCode = System.Net.HttpStatusCode.NotFound;
                    return httpResponseMessage;
                }
                httpResponseMessage.Content = new StringContent(File.ReadAllText(path), Encoding.UTF8);
                httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
                return httpResponseMessage;
            }

               8.新建站点页面

                  站点根目录下新建Script文件夹,下载添加query-1.6.4.min.js,新建Index.html,添加如下代码:

    <!DOCTYPE html>
    <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8" />
        <title>Owin默认页</title>
        <!--通过站点接口,下载Jquery-->
        <script src="getresource?filename=scripts/jquery-1.6.4.min.js"></script>
        <script type="text/javascript">
            $(function () {$('body').append("<h1>Hello Owin!</h1>") })
        </script> 
    </head>
    <body> 
    </body>
    </html>

                  运行重新刷新,页面

            

             至此,解决了Owin Self Hosted Console 程序加载页面的问题,下一篇将在此基础上新建SignalR程序!

  • 相关阅读:
    Leetcode Spiral Matrix
    Leetcode Sqrt(x)
    Leetcode Pow(x,n)
    Leetcode Rotate Image
    Leetcode Multiply Strings
    Leetcode Length of Last Word
    Topcoder SRM 626 DIV2 SumOfPower
    Topcoder SRM 626 DIV2 FixedDiceGameDiv2
    Leetcode Largest Rectangle in Histogram
    Leetcode Set Matrix Zeroes
  • 原文地址:https://www.cnblogs.com/andayhou/p/8418982.html
Copyright © 2011-2022 走看看