System.Web.HttpRequestValidationException:从客户端检测到潜在危险的Request.Form值

当出现上述异常时,通常建议使用以下属性禁用验证请求

    [ValidateInput(false)]
    public ActionResult Save(string content)
    {
        System.IO.File.WriteAllText(fileName, content);
        return View();
    }

那为什么还要提出这种验证呢? 如何正确处理此异常?

===============>>#1 票数:1 已采纳

当URL请求(您的示例: string content )包含危险的关键字:“>,?,<等...”时。 如果要处理此异常(示例:允许这些异常),则可以遵循示例代码:

using System;
using System.Web.Mvc;

namespace Custom {
    public class CustomValidateInput : FilterAttribute, IAuthorizationFilter {
        /// <summary>
        /// Called when authorization is required.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        /// <exception cref="System.ArgumentNullException">filterContext</exception>
        public void OnAuthorization(AuthorizationContext filterContext) {
            if (filterContext == null) {
                throw new ArgumentNullException("filterContext");
            }

            //Set disable validation request
            filterContext.Controller.ValidateRequest = false;

            //----------Your code handle here------------//

        }
    }
}

[CustomValidateInput]
public ActionResult Save(string content)
{
    System.IO.File.WriteAllText(fileName, content);
    return View();
}

  ask by user2217261 translate from so

未解决问题?本站智能推荐:

关注微信公众号