有意思的OWIN,附脱离iis的webapi
Posted darren-xia
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了有意思的OWIN,附脱离iis的webapi相关的知识,希望对你有一定的参考价值。
程序引用
using Owin;
using Microsoft.Owin.Hosting;
新建一个控制台程序
Program
class Program { static void Main(string[] args) { // string baseAddress = "http://localhost:9000"; string baseAddress = "http://10.136.238.68:9000"; using (WebApp.Start<RESTFULTStartup>(url: baseAddress)) { //HttpClient client = new HttpClient(); Console.WriteLine(baseAddress); Console.ReadLine(); } } }
新建一个路由配置类
RESTFULTStartup
1 public class RESTFULTStartup 2 { 3 public void Configuration(IAppBuilder appBuilder) 4 { 5 // 创建 Web API 的配置 6 var config = new HttpConfiguration(); 7 8 // Web API 路由 9 config.MapHttpAttributeRoutes(); 10 11 //移除XML输出 12 config.Formatters.Remove(config.Formatters.XmlFormatter); 13 14 // 默认的 Web API 路由 15 config.Routes.MapHttpRoute( 16 name: "DefaultApi", 17 routeTemplate: "api/{controller}/{id}", 18 defaults: new { id = RouteParameter.Optional } 19 ); 20 // 将路由配置附加到 appBuilder 21 appBuilder.UseWebApi(config); 22 } 23 }
新建一个自定义控制器类
RESController
特别说明:在控制器上标记[RoutePrefix("api/RES")] 在action方法上标记[Route("Test01")]
1 [RoutePrefix("api/RES")] 2 public class RESController : ApiController 3 { 4 //[Route("Test01/{obj:int}")] 5 [Route("Test01")] 6 [HttpPost] 7 public string Test01(dynamic obj) 8 { 9 StringWriter sw = new StringWriter(); 10 try 11 { 12 sw.WriteLine("Test01"); 13 sw.WriteLine("开始"); 14 sw.WriteLine(DateTime.Now.ToString()); 15 string requJSON = JsonConvert.SerializeObject(obj); 16 sw.WriteLine(requJSON); 17 sw.WriteLine("结束"); 18 var x = new 19 { 20 code = "0", 21 desc = "success" 22 }; 23 string jsonX = JsonConvert.SerializeObject(x); 24 sw.WriteLine("返回值:"+ jsonX); 25 return jsonX; 26 } 27 catch (Exception ex) 28 { 29 sw.WriteLine(ex.Message); 30 sw.WriteLine(ex.StackTrace); 31 throw; 32 } 33 finally 34 { 35 System.IO.File.WriteAllText("d:\1fapi\" + Guid.NewGuid() + ".txt", sw.ToString()); 36 } 37 38 } 39 40 //[Route("Test01/{obj:int}")] 41 [Route("Test02")] 42 [HttpPost] 43 public string Test02(dynamic obj) 44 { 45 StringWriter sw = new StringWriter(); 46 try 47 { 48 sw.WriteLine("Test02"); 49 sw.WriteLine("开始"); 50 sw.WriteLine(DateTime.Now.ToString()); 51 string requJSON = JsonConvert.SerializeObject(obj); 52 sw.WriteLine(requJSON); 53 sw.WriteLine("结束"); 54 var x = new 55 { 56 code = "0", 57 desc = "success" 58 }; 59 string jsonX = JsonConvert.SerializeObject(x); 60 sw.WriteLine("返回值:" + jsonX); 61 return jsonX; 62 } 63 catch (Exception ex) 64 { 65 sw.WriteLine(ex.Message); 66 sw.WriteLine(ex.StackTrace); 67 throw; 68 } 69 finally 70 { 71 System.IO.File.WriteAllText("d:\2fapi\" + Guid.NewGuid() + ".txt", sw.ToString()); 72 } 73 } 74 }
最后运行,就可以实现webapi类似的需求
以上是关于有意思的OWIN,附脱离iis的webapi的主要内容,如果未能解决你的问题,请参考以下文章
OWIN 自宿主模式WebApi项目,WebApi层作为单独类库供OWIN调用