1. 如何使用 Web API 来对 MVC 应用程序进行身份验证
首先,让我们先更新 API 项目
我们将先对 API 项目进行必要的修改,修改完成之后再切换到 Web 项目对客户端进行更新。
第1步:我们需要一个数据库
在能做任何操作之前我们需要先创建一个数据库。本例中将使用 SQL Server Express。如果你没有安装,可以从这里下载 SQL Server Express。安装完成之后,创建一个名为 CallingWebApiFromMvc 的数据库。这就是第一步要做的。
Api 项目还需要一个数据库连接字符串,否则我们寸步难行。把下面这段代码插入到 Api 项目的Web.config 文件中:
<connectionStrings>
<add name="ApiFromMvcConnection" connectionString="Data Source=(local);Initial Catalog=CallingWebApiFromMvc;Integrated Security=True" providerName="System.Data.SqlClient" /></connectionStrings>
认证(Identity)框架会自动创建我们管理用户所需要的成员关系表,现在不需要担心去提前创建它们。
2. net webapi 能不能使用mvc的过滤器
这个很有用的,13个扩展点中过滤器占重要的地位。自定义身份验证、自定义post表单时自动检测错误、自定义发生异常时的自动化处理、等等应用。一定要搞明白的。
3. webAPI如何实现整体拦截
e things go wrong Love is meant to be a spirit that
4. .net core中如何在执行action前植入一个webapi过滤器
新建一个MyFilter.cs
public class MyFilter: Attribute,IAuthorizationFilter
实现 OnAuthorization 验证
public class MyFilter : Attribute,IActionFilter,IOrderedFilter
实现 OnActionExecuted(请求方法后)和专 OnActionExecuting(请求方法前)
Startup.cs中ConfigureServices方法中 注册属此MyFilter.cs
services.AddMvc(config => config.Filters.Add(new MyFilter()));
5. 如何使 WebAPI 自动生成漂亮又实用在线API文档
1.1 SwaggerUI
SwaggerUI 是一个简单的Restful API 测试和文档工具。简单、漂亮、易用(官方)。通过读取JSON 配置显示API. 项目本身仅仅也只依赖一些 html,css.js静态文件. 你可以几乎放在任何Web容器上使用。
1.2 Swashbuckle
Swashbuckle 是.NET类库,可以将WebAPI所有开放的控制器方法生成对应SwaggerUI的JSON配置。再通过SwaggerUI 显示出来。类库中已经包含SwaggerUI 。所以不需要额外安装。
2.快速开始
创建项目 OnlineAPI来封装网络音乐服务(示例下载) ,通过API可以搜索、获取音乐的信息和播放连接。
我尽量删除一些我们demo中不会用到的一些文件,使其看上去比较简洁。
WebAPI 安装 Swashbuckle
Install-Package Swashbuckle
代码注释生成文档说明。
Swashbuckle 是通过生成的XML文件来读取注释的,生成 SwaggerUI,JSON 配置中的说明的。
安装时会在项目目录 App_Start 文件夹下生成一个 SwaggerConfig.cs 配置文件,用于配置 SwaggerUI 相关展示行为的。如图:
将配置文件大概99行注释去掉并修改为
c.IncludeXmlComments(GetXmlCommentsPath(thisAssembly.GetName().Name));
并在当前类中添加一个方法
/// <summary>
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
protected static string GetXmlCommentsPath(string name)
{
return string.Format(@"{0}\bin\{1}.XML", AppDomain.CurrentDomain.BaseDirectory, name);
}
紧接着你在此Web项目属性生成选卡中勾选 “XML 文档文件”,编译过程中生成类库的注释文件
添加网络音乐 3个API
访问 http://<youhost>/swagger/ui/index,最终显示效果
我们通过API 测试API 是否成功运行
3.添加自定义HTTP Header
在开发移动端 API时常常需要验证权限,验证参数放在Http请求头中是再好不过了。WebAPI配合过滤器验证权限即可
首先我们需要创建一个 IOperationFilter 接口的类。IOperationFilter
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Http.Description;
using System.Web.Http.Filters;
using Swashbuckle.Swagger;
namespace OnlineAPI.Utility
{
public class HttpHeaderFilter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry
schemaRegistry, ApiDescription apiDescription)
{
if (operation.parameters == null) operation.parameters = new
List<Parameter>();
var filterPipeline =
apiDescription.ActionDescriptor.GetFilterPipeline();
//判断是否添加权限过滤器
var isAuthorized = filterPipeline.Select(filterInfo =>
filterInfo.Instance).Any(filter => filter is IAuthorizationFilter);
//判断是否允许匿名方法
var allowAnonymous =
apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
if (isAuthorized && !allowAnonymous)
{
operation.parameters.Add(new Parameter
{
name = "access-key",
@in = "header",
description = "用户访问Key",
required = false,
type = "string"
});
}
}
}
}
在 SwaggerConfig.cs 的 EnableSwagger 配置匿名方法类添加一行注册代码
c.OperationFilter<HttpHeaderFilter>();
添加Web权限过滤器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using Newtonsoft.Json;
namespace OnlineAPI.Utility
{
/// <summary>
///
/// </summary>
public class AccessKeyAttribute : AuthorizeAttribute
{
/// <summary>
/// 权限验证
/// </summary>
/// <param name="actionContext"></param>
/// <returns></returns>
protected override bool IsAuthorized(HttpActionContext actionContext)
{
var request = actionContext.Request;
if (request.Headers.Contains("access-key"))
{
var accessKey = request.Headers.GetValues("access-key").SingleOrDefault();
//TODO 验证Key
return accessKey == "123456789";
}
return false;
}
/// <summary>
/// 处理未授权的请求
/// </summary>
/// <param name="actionContext"></param>
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
var content = JsonConvert.SerializeObject(new {State = HttpStatusCode.Unauthorized});
actionContext.Response = new HttpResponseMessage
{
Content = new StringContent(content, Encoding.UTF8, "application/json"),
StatusCode = HttpStatusCode.Unauthorized
};
}
}
}
在你想要的ApiController 或者是 Action 添加过滤器
[AccessKey]
最终显示效果
4.显示上传文件参数
SwaggerUI 有上传文件的功能和添加自定义HTTP Header 做法类似,只是我们通过特殊的设置来标示API具有上传文件的功能
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Description;
using Swashbuckle.Swagger;
namespace OnlineAPI.Utility
{
/// <summary>
///
/// </summary>
public class UploadFilter : IOperationFilter
{
/// <summary>
/// 文件上传
/// </summary>
/// <param name="operation"></param>
/// <param name="schemaRegistry"></param>
/// <param name="apiDescription"></param>
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (!string.IsNullOrWhiteSpace(operation.summary) && operation.summary.Contains("upload"))
{
operation.consumes.Add("application/form-data");
operation.parameters.Add(new Parameter
{
name = "file",
@in = "formData",
required = true,
type = "file"
});
}
}
}
}
在 SwaggerConfig.cs 的 EnableSwagger 配置匿名方法类添加一行注册代码
c.OperationFilter<UploadFilter>();
API 文档展示效果
6. 如何在webapi中使用filter
在webapi项目中新建一个MyTestFilter类
这里需要重写两个方法
OnActionExecuting 执行前调用
OnActionExecuted 执行后调用
可以把aop操作写在相应的方法中
这里就不解释具体的aop操作了,只演示一下在方法中获得可能用到的参数
如果要在filter中获得 public string Get(string id)中的id
public override void OnActionExecuting(HttpActionContext actionContext)
actionContext.ActionArguments["id"] 或 actionContext.ActionArguments.TryGetValue("id", out data)
在filter中获得最终的返回值
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
var objectContent = actionExecutedContext.Response.Content as ObjectContent;
var value = objectContent.Value
然后再webapi项目中随便哪个带参数的get上加[MyTestFilter]
7. c#webapi接口怎么加上安全校验
下面这几个注意事项或许可以帮你一些
1. 找到Web应用所有的输入点,找到所有的能接受用户输入的地方,漏掉输入点也就漏掉了可能存在的缝。
2. 过滤每一个输入点,为每个输入点设定相应的校验规则和边界。
3. 不要忘记校验哪些隐藏域,cookie和url参数。
4. 验证从数据库里面得到的数据,这个是最容易忽视的地方,不要相信来自数据库里面的数据就是合法的数据。
5. 你是如何做输入校验的? javascript?如果只是用javascript做客户端校验, 风险还是很大的,一定要确保加上服务端的校验,否则如果客户端禁用了javascript或者客户端代码被人工修改,非法数据还是会进入系统内部的。
6. 隐藏异常信息,再周全的校验也不可能覆盖所有的case,如果非法数据造成了系统的异常,不要将详细的异常信息暴露给客户端,这些异常信息有可能成为系统的攻击入口。
在做输入校验的时候,从“什么样的输入才是合法的”入手会降低验证失效的风险,应该只为每个输入点的输入内容制定一个有限的,刚好够用的合法范围,除此之外的所有内容都当做是非法的。而从“什么样的输入是不合法的”入手则会增加验证失效的可能,因为你不可能穷举非法的输入。
8. webapi做了authorizationfilterattribute验证前端怎么调用
取决复于api的加密方式。制
如加密方式为bearer token的方式。
调用一个需要验证的api步骤是:
POST请求接口:http://ip地址/api/token
参数:{"username":"xxx","password":"xxx","grant_type":"password"} http请求头:{"Content-Type":"application/x-www-form-urlencoded"}
第一个接口会返回一个"access_token"(以下称为token)。请求需要验证接口的api时,http头上加入:{"Authorization:bearer [token]"}即可。
9. webapi接口访问验证是否登陆的解决方案!
不知道你是后台还是前端..
后台:
登陆后.记录登录状态到session里 每次查一篇专即可
前端:
登录后属,记录登录状态或者用户ID到cook or localStorage or sessionStorage or window(不推荐)想知道是否登录检查一片即可