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盘点的更多相关文章

  1. 用ASP创建API。NET Core (Day2):在ASP中创建API。网络核心

    下载PDF article - 1.5 MB 下载source - 152.4 KB 下载source - 206.3 KB 下载source code from GitHub 表的内容 中间件路线图 ...

  2. asp web api 怎么使用put和delete。

    Method Overriding RESTful services allow the clients to act on the resources through methods such as ...

  3. asp .net api 日志

    方法1:继承IExceptionLogger ExceptionLogger是框架提供的表示未处理的异常记录器的抽象类 public class RecordExceptionLogger : Exc ...

  4. ASP.NET API(MVC) 对APP接口(Json格式)接收数据与返回数据的统一管理

    话不多说,直接进入主题. 需求:基于Http请求接收Json格式数据,返回Json格式的数据. 整理:对接收的数据与返回数据进行统一的封装整理,方便处理接收与返回数据,并对数据进行验证,通过C#的特性 ...

  5. Asp.net Api中使用OAuth2.0实现“客户端验证”

    一.实现继承自OAuthAuthorizationServerProvider的类,实现以"客户端验证"方式传入的相关认证和access_token发放. public class ...

  6. ASP.NET API Helper Page 创建并生成相关帮助文档

    创建API项目 修改原工程文件,该行为是为了避免和引入第三方API工程文件冲突 修改发布设置 引入需要生成文档的相关文件,将第三方API依赖的相关文件(XML文件非常重要,是注释显示的关键),复制到文 ...

  7. asp.net api 使用SSL 加密登陆 思路

    < ![CDATA[ 1. 首先 是 要设置iis 2.更改站点使用htpps 3.如果使用的是 iis express 4.如果不是使用https访问.就返回提示信息, 这个要写代码了 pub ...

  8. asp web api json 序列化后 把私有字段信息也返回了解决办法

    serialization returns private properties Are your types marked as [Serializable]? Serializable means ...

  9. Asp.Net Api+Swagger控制器注释

    Swagger注释不显示,只需要进入Startup.cs 找到: c.IncludeXmlComments(Path.Combine(AppDomain.CurrentDomain.BaseDirec ...

随机推荐

  1. zw版【转发·台湾nvp系列Delphi例程】HALCON SetGray

    zw版[转发·台湾nvp系列Delphi例程]HALCON SetGray SetGray_Delphi.PNG unit Unit1;interfaceuses Windows, Messages, ...

  2. 评playerc网友的"求比指定数大且最小的“不重复数”问题"

    问题见:对Alexia(minmin)网友代码的评论及对“求比指定数大且最小的‘不重复数’问题”代码的改进 .算法:求比指定数大且最小的“不重复数”问题的高效实现 . playerc网友的代码如下(求 ...

  3. 【Winfrom】简单的焦点设置问题

    原文: http://blog.csdn.net/zlwzlwzlw/article/details/8573921 初始的时候希望指定控件的焦点 不能用load事件 要用Activated事件才行 ...

  4. 关于学习keynote

    下午在学习如何用keynote写出高大上的文档,看到公司内的一个妹纸洋洋洒洒的写了好多篇文章,顿时觉得自己的知识面狭窄,文科女和理科女的差别,从我嘴里半天吐不出一个富有诗情画意的词句来,那么还是脚踏实 ...

  5. linux C判断文件是否存在【转】

    转自:http://blog.csdn.net/kingjo002/article/details/8442146 一.access函数 功能描述: 检查调用进程是否可以对指定的文件执行某种操作. 用 ...

  6. 转:Spring AOP术语

    1.连接点(Joinpoint)       程序执行的某个特定位置:如类开始初始化前.类初始化后.类某个方法调用前.调用后.方法抛出异常后.这些代码中的特定点,称为“连接点”.Spring仅支持方法 ...

  7. PHP的一些常用汇总

    1. 使用strcmp()函数[区分大小写] 和strcasecmp()函数按照字节比较.比较结果显示:前和后相同为0,前>后为大于0,前<后为小于0. 2. 格式化字符串:number_ ...

  8. The C++ Standard Library --- A Tutorial Reference 读书笔记

    5.2 Smart Pointer(智能指针) shared_ptr的aliasing构造函数,接受一个shared pointer和一个raw pointer.它允许你掌握一个事实:某对象拥有另一个 ...

  9. python:Xml

    <data> <country name="Liechtenstein"> <rank updated="yes">2< ...

  10. 【转】SVN服务器搭建--Subversio与TortoiseSVN的配置安装

    转载地址:http://blog.csdn.net/xinxin19881112/article/details/6410263 1.  Subversio和TortoiseSVN 简介 Subver ...