I have an ASP.NET WebApi application that has some controller methods that expect certain strings to be passed in as method parameters (declared as part of the route template).
On all the methods, the strings passed in are base64-encoded -- which means each controller method must base64-decode them before doing anything with them. While I can obviously have each method do this easily enough, I was wondering if there was a way to perform the decoding before the string actually gets passed to the controller method. I presume this is something along the lines of an action filter or custom formatter, but I'm not familiar enough with asp.net web api to know where to start on that?
Summary:
I've got route templates like : {controller}/{encodedString}/whatever
where {encodedString} is always a base64-encoded string.
and controllers with methods like
GetWhatever(string encodedString)
{
Base64Decode(encodedString);
// do other stuff...
}
I would like to use some part of the asp.net webapi pipeline to decode {encodedString} before the controller method is actually called. What path should I start down in order to do this?
You can create a custom model binder and attach it to the parameters using the ModelBinderAttribute. In the model binder you then do the base64 decoding.
For a reference on parameter binding in Web API check:
How WebAPI does Parameter Binding
Related
I have the following method signature for an action on an MVC controller:
public ActionResult DoSomething(int id, string anotherParameter, IEnumerable<StronglyTypedThing> data)
{
}
This method is called by an AJAX Request (in this instance I'm using ExtJS, but that should have little/no bearing on this I imagine!) which passes up, for example:
id: 1,
anotherParameter: 'cake',
data: '<stronglyTypedThings>
<stronglyTypedThing>
<id>1</id>
<anotherProperty>Smith, John></anotherProperty>
</stronglyTypedThing>
<stronglyTypedThing>
<id>2</id>
<anotherProperty>Doe, Jane></anotherProperty>
</stronglyTypedThing>
</stronglyTypedThings>'
Currently the method signature I've shown above is not what I have, instead the final parameter is defined as string data and I have what is effectively boilerplate code which transforms the XML string into an IEnumerable<StronglyTypedThing>.
Is there a way to have (either by virtue of something baked into MVC, or by extending it) MVC deal with the grunt-work for me so I don't have the boilerplate code present in my action method?
You can create a custom model binder.
This link will have an example of custom xml binder: http://lostechies.com/jimmybogard/2011/06/24/model-binding-xml-in-asp-net-mvc-3/
You might want to look into a custom ValueProviderFactory.
A custom XmlValueProviderFactory will parse the incoming xml string and construct an intermediate dictionary. (which MVC uses to model bind)
Based on your need, you could parse the whole XML/or a part of it, to construct the dictionary equivalent of your Model object. Once there, MVC will take care of creating the Model for you using Model Binding. Also, value providers have the additional benefit of input validation which custom model binders don't have.
Please see following help links to see a JSON & XML Value Provider factory.
i think the JSON Value provider is now in built, but not the XML one. not sure.
http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx/
http://www.nogginbox.co.uk/Media/files/XmlValueProviderFactory.txt
I need to develop a web method that has many parameters. In REST, I understand a webservice has its own significance by attaching itself to particular entity and HttpVerb determines operation type.
This webmethod cannot be associated with an entity, it just calls a stored procedure and returns data, so I assume it only has only a GET method. But it has too many parameters to be fit into a URL. So, do I need to consider using POST method instead of GET.
It wouldn't really pass as 100% true to REST but you can have one web method that you call that looks at query string part of the url to get the additional parameters.
You would have a web method with a route of '/GetData'.
domain.com/GetData?Parameters=firstParm=1^secondParm=info^thirdParm=test
then in the web method, you would check the query string for Parameters and then split the string by the '^' symbol.
or
domain.com/GetData?firstParm=1&secondParm=info&thirdParm=test
this you would have to do a query string for each parameter.
I have read the Spring documentation and I was not able to find relevant information regarding the expected behavior of a Spring MVC controller method returning null (with a return type of String).
Can someone please provide a reply or direct me to relevant documentation? Or to put it another way, what would be the benefit of returning null from a Spring MVC controller method?
In Spring 2, when you returned null from a controller you were saying to the Spring dispatcher that you don't want it to search for a view.
You did this if you were handling the response yourself by writing the response content directly and then flushing the output stream (you were managing a file download for example).
If you didn't return null, Spring would have forwarded to a view who would try to write to the response also, messing up your already written data or resulting in an exception if the response was already commited.
Returning null was a way of saying back off to Spring's view resolver.
A lot of things changed in Spring 3 and now the same can be obtained by having an #RequestMapping annotated method that returns void.
If you have a return type of String but you return null I think that it uses the default RequestToViewNameTranslator for translating an incoming HttpServletRequest into a logical view name when the view name wasn't explicitly supplied.
Return type String in spring mvc generally returns your view resolver, it can be your JSP, html or any other view page.
http://www.mkyong.com/spring3/spring-3-mvc-hello-world-example/
Suppose you want to return a normal String like "hi", you can use #ResponseBody annotation to do this.
I'm using AJAX to send JSON data from web page to back end, and need some validation strategies. I noticed that there're several ways to validate form parameters like SimpleFormController with ValidationUtils class and similar command object binding methods. But is there any suggestion to validate JSON data?
Thanks for even
Avoid the whole controller hierarchy. It is obsolete. Use the new restful style in spring mvc (available in 2.5, improved in 3.0).
There, you can define:
#RequestMapping("/url/foo")
public String handleFooInput(#Valid YourObject obj) { .. }
This will bind the input JSON to the object you specify, and will validate it (if it is annotated with javax.validation annotations). Three preconditions to that:
have jackson and jackson-mapper on your classpath, so that an object is created based on the JSON input
have a javax.validation provider (hibernate-validator for example) on the classpath
put <mvc:annotation-driven /> in your dispatcher-servlet.xml
I have a .NET 3.5 aspx place with a method marked with the [WebMethod] attribute. I'm calling this with jQuery, sending JSON in both directions. This all works great. My question is, what does [ScriptMethod] do when applied to an method? I've tried this and it seems to yield the same result. Are ScriptMethod and WebMethod identical and interchangeable, or does one provide functionality and/or overhead that the other doesn't? In general, I find myself confused with all of the options available for implementing web services and I'd like to know what the pros and cons are for each.
You use the ScriptMethod attribute in the following 2 scenarios.
You are using jquery or any other ajax request mechanism, but you want the request to be a GET not a POST.
You want to receive an XML formated response in javaScript.
If you don't have one of the above requirements; you just need a JSON response using a an ajax request then you can simply use the WebMethod.
There is still one more confusing element here, when do you use the ScriptService attribute? this is used if you are using the Microsoft Ajax Client script framework, this attributes tell the server to generate proxy objects on the client so that you can call functions just like a normal object. var MyRemoteObject = new RemoteObject(); MyRemoteObject.getMessage(....) and even when you use the ScriptService attribute you don't need to add the ScriptMethod attribute only in the above scenarios.
It was confusing to me at the begining because i thought that the ScriptService and the ScriptMethod attributes works together just like the WebService and WebMethod attributes.
The ScriptMethodAttribute attribute is optional. (However, methods that can be called from client script must have the System.Web.Services..::.WebMethodAttribute attribute applied.). If a method is not marked with ScriptMethodAttribute, the method will be called by using the HTTP POST command and the response will be serialized as JSON. You cannot override this setting from script.
from - http://msdn.microsoft.com/en-us/library/system.web.script.services.scriptmethodattribute.aspx
EDIT: WebMethod and ScriptMethod are not competing attributes. ScriptMethod could be an additional annotation, as the above para says.