简体   繁体   中英

How can I get around ASMX's input validation

I am creating a web service using C# asmx. I want to perform my own input validation inside of each web method. As I was writing the code, I realised that asmx itself validates the input before the input gets to the web method, thus stopping me from performing the validation myself. Let me show you what I mean.

Say I have a web method like this:

[WebMethod]
public string method(int param1)
    {
       Validate(param1)
    }

If the person calling method passes a for param1 , then asmx itself will thrown an exception before I can do my own validation. (It throws an exception because a is not of type int .)

Now, I could just make param1 a string, then anything the user puts in param1 would be valid according to asmx's validation. But this is undesirable for reasons I won't go into here.

Is there a way to achieve what I am trying to achieve without making all of the parameters of type string ? If not, it's not the end of the world, as I can make it work, but I would like to know if there is a way.

PS I know asmx is outdated, but my company has told me to use it.

EDIT: I will say one more thing to help you get my problem. I want my web service to return a json string with a specific structure in all cases, even when the input is invalid. In the case that the input is invalid, a json string explainig the issue should be returned. But I can't do this in the case of the input being invalid, as asmx thrown an exception before the request gets to my web method.

I understand why asmx is legacy. The fact that it doesn't let you control the input validation is ridiculous.

I figured it out.

You need to create a class that defines the input in terms of strings. Then make this class the type of the input parameter of the web method. ASMX will deserialize the input into an instance of the class. This is great for a number of reasons:

  • (1) as the class only contains strings, no exception can be thrown by ASMX
  • (2) you can completely control the names of the input parameters from the class. This is a big plus for the DRY principle.

Here I define my input:

    public abstract class Input
    {

    }

    public class CreatePendingOrderInput : Input
    {
        public string customerNo;
        public string callingCountry;
    }
}

Now just hook this up with a web method:

  [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string CreatePendingOrder(CreatePendingOrderInput input)
        {
            return  JsonConvert.SerializeObject((IVRProcesses.Process<CreatePendingOrderOutput>(IVRProcesses.CreatePendingOrder, input)));
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM