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

Asked

Viewed 856 times

8

I’m trying to set up a file upload process for a web service done on c# .asmx, but I am not able to manipulate the sending of parameters through the method POST.

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 parameter token is an identifier I will receive from client to be able to create a temporary directory where the files will be stored as they are received.

So in the client, using the jquery.uploadfile, mount the form to upload the files:

<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 documentation, I can use both the method dynamicFormData as the attribute formData, passing my parameter directly to it.

Example:

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

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

However, just take the parameter from the header of the webMethod and I can already get the break-point, added within the webMethod for debug, is activated.

[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 the token, works. Of course that’s not how I need it, it’s only for tests.

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

1 answer

3


There was nothing wrong with your method. 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 in the form, and then you can recover on the server side using Httpcontext.Current.Request.Form.Get("token");

The Internal Server Error you were probably getting was this error :

System.Invalidoperationexception: Request format invalid: Multipart/form-data; Boundary=---blahblahblah

Browser other questions tagged

You are not signed in. Login or sign up in order to post.