development

ASP.NET MVC 사용자 지정 modelbinder를 사용할 때 클라이언트에서 잠재적으로 위험한 Request.Form 값이 검색되었습니다.

big-blog 2020. 9. 2. 19:46
반응형

ASP.NET MVC 사용자 지정 modelbinder를 사용할 때 클라이언트에서 잠재적으로 위험한 Request.Form 값이 검색되었습니다.


여기에 오류가 발생합니다.

ValueProviderResult value = bindingContext.ValueProvider.GetValue("ConfirmationMessage");

값 선택 만 허용하려면 어떻게합니까?

[ValidateInput(false)]
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    ValueProviderResult value = bindingContext.ValueProvider.GetValue("ConfirmationMessage");
    ValueProviderResult value2 = bindingContext.ValueProvider.GetValue("ConfirmationMessage2");
}

몇 가지 옵션이 있습니다.

모델에서 HTML을 허용하는 데 필요한 각 속성에이 속성을 추가 합니다.

using System.Web.Mvc;

[AllowHtml]
public string SomeProperty { get; set; }

컨트롤러 작업에서이 속성을 추가하여 모든 HTML을 허용합니다.

[ValidateInput(false)]
public ActionResult SomeAction(MyViewModel myViewModel)

web.config의 무차별 대입- 절대 권장하지 않음

web.config 파일의 태그 내에 requestValidationMode = "2.0"속성이있는 httpRuntime 요소를 삽입하십시오. 또한 pages 요소에 validateRequest = "false"속성을 추가하십시오.

<configuration>
  <system.web>
   <httpRuntime requestValidationMode="2.0" />
  </system.web>
  <pages validateRequest="false">
  </pages>
</configuration>

추가 정보 : http://davidhayden.com/blog/dave/archive/2011/01/16/AllowHtmlAttributeASPNETMVC3.aspx

위의 내용은 기본 modelbinder 사용에 적용됩니다.

커스텀 ModelBinder

위 코드에서 bindingContext.ValueProvider.GetValue ()에 대한 호출은 속성에 관계없이 항상 데이터의 유효성을 검사하는 것으로 보입니다. ASP.NET MVC 소스를 살펴보면 DefaultModelBinder가 먼저 요청 유효성 검사가 필요한지 확인한 다음 유효성 검사가 필요한지 여부를 나타내는 매개 변수를 사용하여 bindingContext.UnvalidatedValueProvider.GetValue () 메서드를 호출합니다.

안타깝게도 프레임 워크 코드는 봉인되어 있거나 비공개이거나 무지한 개발자가 위험한 작업을 수행하지 못하도록 보호하기 위해 사용할 수 없습니다.하지만 AllowHtml 및 ValidateInput 속성을 존중하는 작동하는 사용자 지정 모델 바인더를 만드는 것은 그리 어렵지 않습니다.

public class MyModelBinder: IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        // First check if request validation is required
        var shouldPerformRequestValidation = controllerContext.Controller.ValidateRequest && bindingContext.ModelMetadata.RequestValidationEnabled;

        // Get value
        var valueProviderResult = bindingContext.GetValueFromValueProvider(shouldPerformRequestValidation);
        if (valueProviderResult != null)
        {
            var theValue = valueProviderResult.AttemptedValue;

            // etc...
        }
    }
}

다른 필수 부분은 검증되지 않은 값을 검색하는 방법입니다. 이 예제에서는 ModelBindingContext 클래스에 대한 확장 메서드를 사용합니다.

public static class ExtensionHelpers
{
    public static ValueProviderResult GetValueFromValueProvider(this ModelBindingContext bindingContext, bool performRequestValidation)
    {
        var unvalidatedValueProvider = bindingContext.ValueProvider as IUnvalidatedValueProvider;
        return (unvalidatedValueProvider != null)
          ? unvalidatedValueProvider.GetValue(bindingContext.ModelName, !performRequestValidation)
          : bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
    }
}

More info on this at http://blogs.taiga.nl/martijn/2011/09/29/custom-model-binders-and-request-validation/


Try:

HttpRequestBase request = controllerContext.HttpContext.Request;
string re = request.Unvalidated.Form.Get("ConfirmationMessage")

Expanding upon the answer from @D-W, in my Edit controller, in iterating over form values, I had to replace all instances of Request.Params.AllKeys with Request.Unvalidated.Form.AllKeys and all instances of Request[key] with Request.Unvalidated.Form[key].

This was the only solution that worked for me.


Here are the steps to encode at client level and decode it at server level:

  1. Post the form using jquery submit method.

  2. In jquery button click event method encode field that you want to post to server. Example:

    $("#field").val(encodeURIComponent($("#field").val()))
    $("#formid").submit();
    
  3. In Controller Level access all form id value using

    HttpUtility.UrlDecode(Request["fieldid"])
    

Sample example:

  • Controller level:

    public ActionResult Name(string id)
    {
    
        CheckDispose();
        string start = Request["start-date"];
        string end = Request["end-date"];
        return View("Index", GetACPViewModel(HttpUtility.UrlDecode(Request["searchid"]), start, end));
    }
    
  • Client level:

    <% using (Html.BeginForm("Name", "App", FormMethod.Post, new { id = "search-form" }))
    { %>
    <div>
    <label  for="search-text" style="vertical-align: middle" id="search-label" title="Search for an application by name, the name for who a request was made, or a BEMSID">App, (For Who) Name, or BEMSID: </label>
    <%= Html.TextBox("searchid", null, new {value=searchText, id = "search-text", placeholder = "Enter Application, Name, or BEMSID" })%>
    </div>
    <div>
    <input id="start-date" name="start-date" class="datepicker" type="text"  placeholder="Ex: 1/1/2012"/>
    </div>
    <div>
    <input id="end-date" name="end-date" class="datepicker" type="text"  placeholder="Ex: 12/31/2012"/>
    </div>
    <div>
    <input type="button" name="search" id="btnsearch" value="Search" class="searchbtn" style="height:35px"/>
    </div> 
    <% } %>
    

In Document Ready function:

$(function () {     
  $("#btnsearch").click(function () {  
    $("#search-text").val(encodeURIComponent($("#search-text").val()));
    $("#search-form").submit();
  });
});

참고URL : https://stackoverflow.com/questions/17254354/asp-net-mvc-a-potentially-dangerous-request-form-value-was-detected-from-the-cli

반응형