var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();//開啟標(biāo)注路由
config.Services.Replace(typeof(IContentNegotiator), new JsonFirstContentNegotiator());//內(nèi)容協(xié)商為jsonFirst,這樣,默認(rèn)使用Json,但是又不影響其他格式.
app.UseWebApi(config);//go
//其他Owin中間件相關(guān)知識(shí),參考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
}//根據(jù)前面配置的JsonFirstContentNegotiator,WebApi會(huì)自動(dòng)返回json對(duì)象
}
}
public class Dto
{
public string Name{get;set;}
public int Age{get;set;}
}