Search code examples
c#file-uploadasp.net-web-api2multipartform-dataform-data

Upload a file and data in same API call c#


After a lot of research, I am posting this question as I couldn't figure it out myself.

The scenario is that I need to pass the following parameters to a HttpPost request in a Web API 2 controller in .Net framework 4.8:

  • Date -> Date object
  • Author -> string
  • Title -> string
  • Content -> string
  • Image -> File object

My front end Angular code is:

saveNewsArticle(data) {
    return new Observable(observer => {
      let apiStr = this.apiStrBase + "SaveNewsArticle";

      let formData = new FormData();
      formData.append('date', data.publishDate);
      formData.append('author', data.author);
      formData.append('title', data.title);
      formData.append('image', data.image);
      formData.append('content', data.content);

      this.httpClient.post(apiStr, formData).subscribe((result) => {
        observer.next({ result: true, data: result });
      },
        error => {
          observer.next({ result: false });
        }
      );
    });
  }

My C# code is:

   [HttpPost]
   public void SaveNewsArticle()
   {
       var date = HttpContext.Current.Request.Params["date"];
       var author = HttpContext.Current.Request.Params["author"];
       var title = HttpContext.Current.Request.Params["title"];
       var content = HttpContext.Current.Request.Params["content"];
       var image = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files[0] : null;
   }

All of this just works fine, but, I'm using a WYSIWYG editor to get the styling of the text and hence the content is html, for example, <p>this is my content</p> and I get this error in c#:

System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client

enter image description here

Following is what I have tried so far:

  1. I don't want to use <httpRuntime requestValidationMode="2.0" />

  2. I can pass it as a model public void SaveArticle(Article article) which gets everything just fine but the image is always null.

  3. I can replace the '<' and '>' and that solves the problem for me but that is not how this should be done. It's a hack.

  4. In MVC we could just use [ValidateInput(false)] or [AllowHtml] but can't use it on Web API 2.

  5. Should I implement a custom formatter to handle the multipart/form-data like done here

Any help/guidance is greatly appreciated.


Solution

  • Alternative ways to submit HTML codes to the controller is

    1. submit as base 64 string
    2. submit as HTML encoded string

    Personally I think base 64 is more straightforward, where in

    JavaScript (Encode)

    formData.append('content', btoa(data.content));
    

    C# (Decode)

    var content = Encoding.UTF8.GetString(Convert.FromBase64String(HttpContext.Current.Request.Params["content"]));