asp.net-web-api – ASP.NET Web API避免查询字符串中的无效参数
发布时间:2020-12-16 07:17:13 所属栏目:asp.Net 来源:网络整理
导读:给定以下Web API控制器操作: // GET api/values public IEnumerablestring Get() { return new string[] { "value1","value2" }; } 即使查询字符串中的参数不存在,执行以下请求也不会失败: http://localhost:22297/api/values?someinvalidparameter=10 有
给定以下Web API控制器操作:
// GET api/values public IEnumerable<string> Get() { return new string[] { "value1","value2" }; } 即使查询字符串中的参数不存在,执行以下请求也不会失败: http://localhost:22297/api/values?someinvalidparameter=10 有没有办法确保查询字符串中的所有参数都是被调用操作的有效参数? 解决方法
您可以编写一个操作过滤器,验证操作参数中是否存在所有查询参数,如果不存在则抛出.
using System; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http.Controllers; using System.Web.Http.Filters; namespace My.Namespace.Filters { /// <summary> /// Action filter that checks that parameters passed in the query string /// are only those that we specified in methods signatures. /// Otherwise returns 404 Bad Request. /// </summary> public class ValidateQueryParametersAttribute : ActionFilterAttribute { /// <summary> /// This method runs before every WS invocation /// </summary> /// <param name="actionContext"></param> public override void OnActionExecuting(HttpActionContext actionContext) { //check that client does not use any invalid parameter //but just those that are required by WS methods var parameters = actionContext.ActionDescriptor.GetParameters(); var queryParameters = actionContext.Request.GetQueryNameValuePairs(); if (queryParameters.Select(kvp => kvp.Key).Any(queryParameter => !parameters.Any(p => p.ParameterName == queryParameter))) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest); } } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- ASP MVC Razor在输入占位符中编码特殊字符
- asp.net – 如何迭代通过自定义vb.net对象的每个属性?
- wcf – 我可以在实体框架4.3中使用RIA服务吗?
- 如何在ASP.NET MVC中使用JQuery调用控制器操作
- 帮助选择ASP.NET的代码生成工具
- 勾选复选框时,禁用一些ASP.Net验证控件
- asp.net – 有没有办法每天在.Net Web应用程序中运行一个进
- asp.net – 需要安装Dnx Runtime软件包 有关详细信息,请参阅
- asp.net-mvc – ASP.NET MVC – 如何访问除Controller和Vie
- 验证 – ASP.NET Web API是否支持IValidatableObject?
推荐文章
站长推荐
- asp.net-web-api – 如何在ASP.NET WebAPI RC中绑
- asp.net – 转发器内的复选框,如何在检查更改功能
- asp.net-mvc – MVC和NOSQL:直接将视图模型保存
- 编辑asp.net razor chtml文件是否需要重新编译?
- asp.net – ASP错误:由于对象的当前状态,操作无
- asp.net – IIS返回找不到.mp4文件的404
- ASP.NET MVC4 WebApi路由中包含文件名
- ASP.NET Core MVC 2.x 全面教程_ASP.NET Core MV
- ASP.NET Core MVC 6中的默认,系统和Mi??crosoft
- ASP.net:我可以在bin文件夹中拥有2个不同版本的
热点阅读