搭建webapi2 Owin环境

搭建环境以及基本配置

  1. 首先创建一个空白Web App 项目.就是选Empty那个,记得不要勾host on cloud/云托管
  2. 然后通过nuget安装下面packages.config内容.
  
  
  
  
  
  
  
  
  
  
  
  
  1. 接着配置Startup.cs,初始化WebApi
        var config = new HttpConfiguration();
        config.MapHttpAttributeRoutes();//开启标注路由
        config.Services.Replace(typeof(IContentNegotiator), new JsonFirstContentNegotiator());//内容协商为jsonFirst,这样,默认使用Json,但是又不影响其他格式.
        app.UseWebApi(config);//go
        //其他Owin中间件相关知识,参考MSDN
    public class JsonFirstContentNegotiator : DefaultContentNegotiator
    {
        private readonly JsonMediaTypeFormatter _jsonFormatter;

        public JsonFirstContentNegotiator(bool indented = true, bool camelcase = true)
        {
            _jsonFormatter = new JsonMediaTypeFormatter();
            var serializerSettings = _jsonFormatter.SerializerSettings;
            if (indented)
                serializerSettings.Formatting = Formatting.Indented;
            if (!camelcase)
                return;
            serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }

        protected override MediaTypeFormatterMatch SelectResponseMediaTypeFormatter(ICollection matches)
        {
            return matches.FirstOrDefault(m => m.Formatter is JsonMediaTypeFormatter) ?? base.SelectResponseMediaTypeFormatter(matches);
        }
    }
  1. 接着可以输出Hello World了,IndexController.cs
    public class IndexController : ApiController
    {
        [HttpGet]
        [Route()]
        public string HelloWorld()
        {
            return "HelloWorld";
        }

        [HttpGet]
        [Route("objectInfo")]
        public Dto GetObjInfo()
        {
            return new Dto{
                Name = "songtin.huang",
                Age = 24
            }//根据前面配置的JsonFirstContentNegotiator,WebApi会自动返回json对象
        }
    }
    public class Dto
    {
        public string Name{get;set;}
        public int Age{get;set;}
    }

你可能感兴趣的:(搭建webapi2 Owin环境)