加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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);
            }
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读