1.自定义ContentNegotiator

/// <summary>
/// 返回json的ContentNegotiator
/// </summary>
public class JsonContentNegotiator : IContentNegotiator
{
private readonly JsonMediaTypeFormatter _jsonFormatter; public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
{
_jsonFormatter = formatter;
} public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
{
return new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
}
}

2.自定义HttpControllerSelector

/// <summary>
/// 设置api支持namespace
/// </summary>
public class NamespaceHttpControllerSelector : DefaultHttpControllerSelector
{
private const string NamespaceRouteVariableName = "namespace_name";
private readonly HttpConfiguration _configuration;
private readonly Lazy<ConcurrentDictionary<string, Type>> _apiControllerCache; public NamespaceHttpControllerSelector(HttpConfiguration configuration)
: base(configuration)
{
_configuration = configuration;
_apiControllerCache = new Lazy<ConcurrentDictionary<string, Type>>(
new Func<ConcurrentDictionary<string, Type>>(InitializeApiControllerCache));
} private ConcurrentDictionary<string, Type> InitializeApiControllerCache()
{
IAssembliesResolver assembliesResolver = this._configuration.Services.GetAssembliesResolver();
var types = this._configuration.Services.GetHttpControllerTypeResolver().GetControllerTypes(assembliesResolver).ToDictionary(t => t.FullName, t => t); return new ConcurrentDictionary<string, Type>(types);
} public IEnumerable<string> GetControllerFullName(HttpRequestMessage request, string controllerName)
{
object namespaceName;
var data = request.GetRouteData();
IEnumerable<string> keys = _apiControllerCache.Value.ToDictionary<KeyValuePair<string, Type>, string, Type>(t => t.Key,
t => t.Value, StringComparer.CurrentCultureIgnoreCase).Keys.ToList(); if (!data.Values.TryGetValue(NamespaceRouteVariableName, out namespaceName))
{
return from k in keys
where k.EndsWith(string.Format(".{0}{1}", controllerName,
DefaultHttpControllerSelector.ControllerSuffix), StringComparison.CurrentCultureIgnoreCase)
select k;
} string[] namespaces = (string[])namespaceName;
return from n in namespaces
join k in keys on string.Format("{0}.{1}{2}", n, controllerName,
DefaultHttpControllerSelector.ControllerSuffix).ToLower() equals k.ToLower()
select k;
} public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
{
Type type;
if (request == null)
{
throw new ArgumentNullException("request");
}
string controllerName = this.GetControllerName(request);
if (string.IsNullOrEmpty(controllerName))
{
throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound,
string.Format("No route providing a controller name was found to match request URI '{0}'", new object[] { request.RequestUri })));
}
IEnumerable<string> fullNames = GetControllerFullName(request, controllerName);
if (fullNames.Count() == 0)
{
throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound, string.Format("No route providing a controller name was found to match request URI '{0}'", new object[] { request.RequestUri })));
} if (this._apiControllerCache.Value.TryGetValue(fullNames.First(), out type))
{
return new HttpControllerDescriptor(_configuration, controllerName, type);
}
throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound, string.Format("No route providing a controller name was found to match request URI '{0}'", new object[] { request.RequestUri })));
}
}

3.注册路由

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//注册返回json的ContentNegotiator,替换默认的DefaultContentNegotiator
var jsonFormatter = new JsonMediaTypeFormatter();
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter)); //注册支持namespace的HttpControllerSelector,替换默认DefaultHttpControllerSelector
config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(GlobalConfiguration.Configuration)); config.Routes.MapHttpRoute(
name: "PC",
routeTemplate: "api/pc/{controller}/{action}/{id}",
defaults: new
{
id = RouteParameter.Optional,
namespace_name = new string[] { "HGL.Web.ApiControllers.PC" }
}
); config.Routes.MapHttpRoute(
name: "Phone",
routeTemplate: "api/phone/{controller}/{action}/{id}",
defaults: new
{
id = RouteParameter.Optional,
namespace_name = new string[] { "HGL.Web.ApiControllers.Phone" }
}
); config.Routes.MapHttpRoute(
name: "ApiDefault",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new
{
id = RouteParameter.Optional,
namespace_name = new string[] { "HGL.Web.ApiControllers" }
}
);
}
}

WebApi自定义返回类型和命名空间实现的更多相关文章

  1. ASP.NET Core WebAPI控制器返回类型的最佳选项

    前言 从.NET Core 2.1版开始,到目前为止,控制器操作可以返回三种类型的WebApi响应.这三种类型都有自己的优点和缺点,但都缺乏满足REST和高可测性的选项. ASP.NET Core中可 ...

  2. webapi的返回类型,webapi返回图片

    1.0 首先是返回常用的系统类型,当然这些返回方式不常用到.如:int,string,list,array等.这些类型直接返回即可. public List<string> Get() { ...

  3. [经验分享]WebAPI中返回类型JsonMessage的应用

    这是一个绝无仅有的好类型,一个你爱不释手的好类型,好了,不扯了,直接上干货. 相信大家都知道,在调用接口的时候返回Json数据已经成为一种不成文的标准,因为它的解析快,易读等优秀的特性,所以被绝大多数 ...

  4. ASP.NET Core 2.2 基础知识(十四) WebAPI Action返回类型(未完待续)

    要啥自行车,直接看手表 //返回基元类型 public string Get() { return "hello world"; } //返回复杂类型 public Person ...

  5. MVC开发中自定义返回类型

    在做项目web的MVC中,会用到返回值的问题,我们一般使用AjaxResult的返回值,根据自己的需要进行自定义,如下参考: using System; using System.Collection ...

  6. C# web api返回类型设置为json的两种方法

    web api写api接口时默认返回的是把你的对象序列化后以XML形式返回,那么怎样才能让其返回为json呢,下面就介绍两种方法: 方法一:(改配置法) 找到Global.asax文件,在Applic ...

  7. WEB API 返回类型设置为JSON 【转】

    http://blog.sina.com.cn/s/blog_60ba16ed0102uzc7.html web api写api接口时默认返回的是把你的对象序列化后以XML形式返回,那么怎样才能让其返 ...

  8. WebApi 接口返回值不困惑:返回值类型详解。IHttpActionResult、void、HttpResponseMessage、自定义类型

    首先声明,我还没有这么强大的功底,只是感觉博主写的很好,就做了一个复制,请别因为这个鄙视我,博主网址:http://www.cnblogs.com/landeanfen/p/5501487.html ...

  9. C#进阶系列——WebApi 接口返回值不困惑:返回值类型详解

    前言:已经有一个月没写点什么了,感觉心里空落落的.今天再来篇干货,想要学习Webapi的园友们速速动起来,跟着博主一起来学习吧.之前分享过一篇 C#进阶系列——WebApi接口传参不再困惑:传参详解  ...

随机推荐

  1. 48.Cookie 管理

    转自:http://www.runoob.com/nodejs/nodejs-express-framework.html 我们可以使用中间件向 Node.js 服务器发送 cookie 信息,以下代 ...

  2. 使用h5 <a>标签 href='url' download 下载踩过的坑

    用户点击下载多媒体文件(图片/视频等),最简单的方式: <a href='url' download="filename.ext">下载</a> 如果url ...

  3. (MySQL里的数据)通过Sqoop Import HBase 里 和 通过Sqoop Export HBase 里的数据到(MySQL)

    Sqoop 可以与HBase系统结合,实现数据的导入和导出,用户需要在 sqoop-env.sh 中添加HBASE_HOME的环境变量. 具体,见我的如下博客: hadoop2.6.0(单节点)下Sq ...

  4. 【Codeforces Round #426 (Div. 2) A】The Useless Toy

    [Link]:http://codeforces.com/contest/834/problem/A [Description] [Solution] 开个大小为4的常量字符数组; +n然后余4,-n ...

  5. 亚马逊AWS的route53的收费,月费最低 0.9 USD

    亚马逊AWS的route53的收费Amazon Route 53 定价 https://aws.amazon.com/cn/route53/pricing/ 一文中,对于一些术语的解释第一项收费--域 ...

  6. js34

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/stri ...

  7. Android学习笔记进阶20之得到图片的缩略图

    <1>简介 之前往往是通过Bitmap.Drawable和Canvas配合完成,需要写一系列繁杂的逻辑去缩小原有图片,从而得到缩略图. 现在我给大家介绍一种比较简单的方法:(网上有) 在A ...

  8. alert警告框

    标签中写: <div class="alert alert-warning fade in"> <button class="close" d ...

  9. error: function declaration isn’t a prototype [-Werror=strict-prototypes]

    "warning: function declaration isn't a prototype" was caused by the function like that:   ...

  10. F的ACM暑期集训计划

    暑假的知识计划(补充中...) 1.数论相关 (7days) 待完成 多项式同余方程/高次同余方程/欧拉函数/克莱姆法则/高斯消元/莫比乌斯反演/伪素数判定/baby-step-gaint-step ...