WebApi自定义返回类型和命名空间实现
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自定义返回类型和命名空间实现的更多相关文章
- ASP.NET Core WebAPI控制器返回类型的最佳选项
前言 从.NET Core 2.1版开始,到目前为止,控制器操作可以返回三种类型的WebApi响应.这三种类型都有自己的优点和缺点,但都缺乏满足REST和高可测性的选项. ASP.NET Core中可 ...
- webapi的返回类型,webapi返回图片
1.0 首先是返回常用的系统类型,当然这些返回方式不常用到.如:int,string,list,array等.这些类型直接返回即可. public List<string> Get() { ...
- [经验分享]WebAPI中返回类型JsonMessage的应用
这是一个绝无仅有的好类型,一个你爱不释手的好类型,好了,不扯了,直接上干货. 相信大家都知道,在调用接口的时候返回Json数据已经成为一种不成文的标准,因为它的解析快,易读等优秀的特性,所以被绝大多数 ...
- ASP.NET Core 2.2 基础知识(十四) WebAPI Action返回类型(未完待续)
要啥自行车,直接看手表 //返回基元类型 public string Get() { return "hello world"; } //返回复杂类型 public Person ...
- MVC开发中自定义返回类型
在做项目web的MVC中,会用到返回值的问题,我们一般使用AjaxResult的返回值,根据自己的需要进行自定义,如下参考: using System; using System.Collection ...
- C# web api返回类型设置为json的两种方法
web api写api接口时默认返回的是把你的对象序列化后以XML形式返回,那么怎样才能让其返回为json呢,下面就介绍两种方法: 方法一:(改配置法) 找到Global.asax文件,在Applic ...
- WEB API 返回类型设置为JSON 【转】
http://blog.sina.com.cn/s/blog_60ba16ed0102uzc7.html web api写api接口时默认返回的是把你的对象序列化后以XML形式返回,那么怎样才能让其返 ...
- WebApi 接口返回值不困惑:返回值类型详解。IHttpActionResult、void、HttpResponseMessage、自定义类型
首先声明,我还没有这么强大的功底,只是感觉博主写的很好,就做了一个复制,请别因为这个鄙视我,博主网址:http://www.cnblogs.com/landeanfen/p/5501487.html ...
- C#进阶系列——WebApi 接口返回值不困惑:返回值类型详解
前言:已经有一个月没写点什么了,感觉心里空落落的.今天再来篇干货,想要学习Webapi的园友们速速动起来,跟着博主一起来学习吧.之前分享过一篇 C#进阶系列——WebApi接口传参不再困惑:传参详解 ...
随机推荐
- How to install Armbian on Orange Pi Plus 2e
bian on Orange Pi Plus 2e How to install Armbian on Orange Pi Plus 2e Armbian on the microSD You jus ...
- 实现CSS样式垂直水平完全居中
1.水平居中 a.内联元素(inline or inline-*)居中? 你可以让他相对父级块级元素居中对齐 .center-children { text-align: center; } b.块级 ...
- 【Codeforces Round #427 (Div. 2) D】Palindromic characteristics
[Link]:http://codeforces.com/contest/835/problem/D [Description] 给你一个字符串; 让你在其中找到1..k阶的回文子串; 并统计它们的数 ...
- POJ——T 2891 Strange Way to Express Integers
http://poj.org/problem?id=2891 Time Limit: 1000MS Memory Limit: 131072K Total Submissions: 16849 ...
- Python批量重命名指定目录下文件的两种方法
#法一 import os path = "C://Python34//" for file in os.listdir(path): if os.path.isfile(os.p ...
- userAgent判断客户端,以及各个浏览器的ua
userAgent判断客户端,以及各个浏览器的ua http://blog.csdn.net/yoyoosyy/article/details/70142884 navigator.userAgent ...
- screen-调节屏幕亮度
今天做项目的时候,需要实现一个功能,就是进入一个应用,在这个应用中,屏幕的亮度变为最亮.关键代码如下 bt1.setOnClickListener(new OnClickListener() { @O ...
- thinkphp缓存使用
thinkphp缓存使用 一.总结 1.这里的缓存不是指的缓存的页面,而是cache,如果你缓存了一个数组,那么你就可以取出这个数组里面的数据进行使用,用法性质和cookie和session有点像 2 ...
- Mysql基本增删改查
1登陆服务器 mysql -h localhost -u username -p password 2查看存在数据库 show databases; 3创建一个数据库(例如名字为class1,以下都是 ...
- javascript: with 表单验证
<html> <head> <script type="text/javascript"> function validate_required ...