ASP.NET API盘点
1.控制只返回JSON一种数据
public class JsonContentNegotiator : IContentNegotiator
{
private readonly JsonMediaTypeFormatter _jsonFormatter;
public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
{
_jsonFormatter = formatter;
}
public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
{
var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
return result;
}
}
使用:在WebApiConfig.cs中
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}",
defaults: new { id = RouteParameter.Optional }
); // 取消注释下面的代码行可对具有 IQueryable 或 IQueryable<T> 返回类型的操作启用查询支持。
// 若要避免处理意外查询或恶意查询,请使用 QueryableAttribute 上的验证设置来验证传入查询。
// 有关详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=279712。
//config.EnableQuerySupport(); // 若要在应用程序中禁用跟踪,请注释掉或删除以下代码行
// 有关详细信息,请参阅: http://www.asp.net/web-api
config.EnableSystemDiagnosticsTracing(); var jsonFormatter = new JsonMediaTypeFormatter();
//optional: set serializer settings here
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
}
2.支持跨域POST,网上很多都是.net 4.5的,找了好久才找到.net 4.0的方法
public class CorsHandler : DelegatingHandler
{
const string Origin = "Origin";
const string AccessControlRequestMethod = "Access-Control-Request-Method";
const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
const string AccessControlAllowHeaders = "Access-Control-Allow-Headers"; protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
bool isCorsRequest = request.Headers.Contains(Origin);
bool isPreflightRequest = request.Method == HttpMethod.Options;
if (isCorsRequest)
{
if (isPreflightRequest)
{
return Task.Factory.StartNew<HttpResponseMessage>(() =>
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First()); string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
if (accessControlRequestMethod != null)
{
response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
} string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
if (!string.IsNullOrEmpty(requestedHeaders))
{
response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
} return response;
}, cancellationToken);
}
else
{
return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>(t =>
{
HttpResponseMessage resp = t.Result;
resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
return resp;
});
}
}
else
{
return base.SendAsync(request, cancellationToken);
}
}
}
使用:在Global.asax中
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles); GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler()); new GZFrameworkDBConfig();
}
ASP.NET API盘点的更多相关文章
- 用ASP创建API。NET Core (Day2):在ASP中创建API。网络核心
下载PDF article - 1.5 MB 下载source - 152.4 KB 下载source - 206.3 KB 下载source code from GitHub 表的内容 中间件路线图 ...
- asp web api 怎么使用put和delete。
Method Overriding RESTful services allow the clients to act on the resources through methods such as ...
- asp .net api 日志
方法1:继承IExceptionLogger ExceptionLogger是框架提供的表示未处理的异常记录器的抽象类 public class RecordExceptionLogger : Exc ...
- ASP.NET API(MVC) 对APP接口(Json格式)接收数据与返回数据的统一管理
话不多说,直接进入主题. 需求:基于Http请求接收Json格式数据,返回Json格式的数据. 整理:对接收的数据与返回数据进行统一的封装整理,方便处理接收与返回数据,并对数据进行验证,通过C#的特性 ...
- Asp.net Api中使用OAuth2.0实现“客户端验证”
一.实现继承自OAuthAuthorizationServerProvider的类,实现以"客户端验证"方式传入的相关认证和access_token发放. public class ...
- ASP.NET API Helper Page 创建并生成相关帮助文档
创建API项目 修改原工程文件,该行为是为了避免和引入第三方API工程文件冲突 修改发布设置 引入需要生成文档的相关文件,将第三方API依赖的相关文件(XML文件非常重要,是注释显示的关键),复制到文 ...
- asp.net api 使用SSL 加密登陆 思路
< ![CDATA[ 1. 首先 是 要设置iis 2.更改站点使用htpps 3.如果使用的是 iis express 4.如果不是使用https访问.就返回提示信息, 这个要写代码了 pub ...
- asp web api json 序列化后 把私有字段信息也返回了解决办法
serialization returns private properties Are your types marked as [Serializable]? Serializable means ...
- Asp.Net Api+Swagger控制器注释
Swagger注释不显示,只需要进入Startup.cs 找到: c.IncludeXmlComments(Path.Combine(AppDomain.CurrentDomain.BaseDirec ...
随机推荐
- SIFT算法详解(转)
http://blog.csdn.net/zddblog/article/details/7521424 目录(?)[-] 尺度不变特征变换匹配算法详解 Scale Invariant Feature ...
- SQL Server 索引视图 聚簇索引
创建示例: 朋友的网站速度慢,让我帮忙看下,他用的SQL Server里面 有一个文章表里面有30多万条记录 还有一个用户表里面也差不多17万记录 偏偏当初设计的时候没有冗余字段 很多帖子信息需要JO ...
- ios7下不能录音问题解决
在ios6上运行非常正常的AVAudioRecoder组件,而跑到ios7上就不能工作了.通过google搜索在stackoverflow上的解决方法.http://stackoverflow.com ...
- XP+devOps开发模式与scrum敏捷开发对比,docker虚拟化
XP+devOps开发模式与scrum敏捷开发对比,docker虚拟化 我们现在用的就是典型的XP+devOps模式,已经放弃scrum了 现在还很多公司弄docker虚拟化docker非常复杂,当然 ...
- laravel5.1启动详解
laravel的启动过程 如果没有使用过类似Yii之类的框架,直接去看laravel,会有点一脸迷糊的感觉,起码我是这样的.laravel的启动过程,也是laravel的核心,对这个过程有一个了解,有 ...
- List对象排序的通用方法
转自 @author chenchuang import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Me ...
- UIView完全置顶的方法
一般来说,若需要独立添加一个UIView,使其覆盖于整个应用窗口之上,是这样实现的: AppDelegate *app = (AppDelegate *)[[UIApplication sharedA ...
- 【jQuery UI 1.8 The User Interface Library for jQuery】.学习笔记.5.Accordion控件
accordion是另一个UI控件,能允许你将一组content加入相互分隔的.能够被浏览者的交互打开或关闭的panels中.因此,它大多数的content在初始化的时候是隐藏的,很像tabs控件.每 ...
- WKWebView与Js实战(OC版)
前言 上一篇专门讲解了WKWebView相关的所有类.代理的所有API.那么本篇讲些什么呢?当然是实战了! 本篇文章教大家如何使用WKWebView去实现常用的一些API操作.当然,也会有如何与JS交 ...
- python: hashlib 加密模块
加密模块hashlib import hashlib m=hashlib.md5() m.update(b'hello') print(m.hexdigest()) #十六进制加密 m.update( ...