搭建环境以及基本配置
- 首先创建一个空白Web App 项目.就是选Empty那个,记得不要勾host on cloud/云托管
- 然后通过nuget安装下面packages.config内容.
<package id="EntityFramework" version="6.1.3" targetFramework="net452" />
<package id="Microsoft.AspNet.Cors" version="5.0.0" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Owin" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.Owin" version="3.0.1" targetFramework="net452" />
<package id="Microsoft.Owin.Cors" version="3.0.1" targetFramework="net452" />
<package id="Microsoft.Owin.Host.SystemWeb" version="3.0.1" targetFramework="net452" />
<package id="Newtonsoft.Json" version="9.0.1" targetFramework="net452" />
<package id="Owin" version="1.0" targetFramework="net452" />
- 接着配置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<MediaTypeFormatterMatch> matches)
{
return matches.FirstOrDefault(m => m.Formatter is JsonMediaTypeFormatter) ?? base.SelectResponseMediaTypeFormatter(matches);
}
}
- 接着可以输出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;}
}