What is the correct way to declare a WebMethod asmx in C # to receive POST requests with parameters?

8

I'm trying to put together a file upload process for a web service done in c # .asmx but I'm not able to manipulate the sending of parameters through the POST method.

This is the webMethod I created:

[WebMethod]
[SoapHeader("UserAuthentication")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void UploadFiles(string token)
{
    CheckHeader();
    if (!(Context.Request.Files.Count > 0))
        return;
    var path = (UserAuthentication.Usuario.Login + token).GetHashCode();
    var directory = DiretorioPublicacaoArquivos();

    foreach (string fileItem in Context.Request.Files.AllKeys) {
        var file = Context.Request.Files[fileItem];

        if (Strings.IsPopulated(file.FileName)) {
            var dirInfo = new DirectoryInfo(directory + @"\temp\" + path+ @"\");
            if (!dirInfo.Exists)
                dirInfo.Create();

            var fileInfo = new FileInfo(dirInfo.FullName + file.FileName);
            if (fileInfo.Exists)
                fileInfo.Delete();

            file.SaveAs(fileInfo.FullName);
        }
    }
}
The token parameter is an identifier that I will receive from the client in order to create a temporary directory where the files will be stored as they are received.

Then in the client , using jquery.uploadfile , I am uploading the file upload form:

<div id="upload">Selecionar Arquivos</div>
$("#upload").uploadFile({
    url: "/Services/PublicacaoService.asmx/UploadFiles",
    method: "post",
    fileName: "myfile",
    dynamicFormData: function () {
        var data = { token: "123 testando" };
        return data;
    },
    multiple: true,
});

According to the plugin's documentation, I can use both the dynamicFormData method and the formData , passing my parameter directly to it.

Example:

$('#fileupload').fileupload({
    formData: {example: 'test'}
});

I've tried both ways, but I can not send files when I need to pass a parameter to webMethod. What happens is that the attached files soon return an Internal Server Error .

However, just get the webMethod header parameter and I can already get the break-point added inside the webMethod to debug , enable it.

[WebMethod]
[SoapHeader("UserAuthentication")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void UploadFiles() // <-- sem o parâmetro
{ 
    ... 
}

Inlusive, manipulating to play in another folder that does not depend on token , works. Of course, this is not how I need it, it's just for testing.

How to resolve this?
What is the correct way to declare WebMethod to receive requests by the POST method and with parameters?     

asked by anonymous 22.08.2014 / 21:27

1 answer

3

With his method there was nothing wrong. So much so that if you test with:

  <script>
        $(document).ready(function () {
             $.ajax(
              {
                   url: "/Services/PublicacaoService.asmx/UploadFiles",
                   contentType: "application/json; charset=utf-8",
                   enctype: 'multipart/form-data',
                   dataType: "json",
                   type: "POST",
                   data: "{token:'test'}"
               });
        });
    </script>

You will see that your method will stop at your break point.

For this plugin, I suggest you change your UploadFiles method to the following:

public void UploadFiles()
{
    var token = HttpContext.Current.Request.Form.Get("token");
    CheckHeader();
    if (!(Context.Request.Files.Count > 0))
    //Continuação do seu código
}

In the plugin when you use dynamicFormData the token is added to the form, and then you can recover on the server side using HttpContext.Current.Request.Form.Get ("token");

The Internal Server Error you received was probably this error:

  

System.InvalidOperationException: Request format   invalid: multipart / form-data; boundary = ---- blahblahblah

    
25.08.2014 / 23:19