How to deal with optional multipart data in Web API Post - asp.net-web-api

I need to create an ASP.NET Web API operation that takes in a few string fields plus an optional file.
Without the file requirement, I can use the standard:
public async Task<IHttpActionResult> Post(MyModel model)
With the file always being required, I can use:
public async Task<IHttpActionResult> Post()
(this then uses a MultipartStreamProvider to extract the file and form data)
Given the fact that the file is optional though, I am not sure as to the best route to take. My android client only uses multipart/form-data if a file is present.
I can have two separate operations which seems inherently wrong. Alternatively, I can try and create a single operation that can handle both multipart/form-data and a normal post but this seems very awkward given the very different approaches required by web api in the two cases. As a third option, I can try to force all calls to use multipart at the android end but this may entail using another library which means more work.
I can't imagine I am the first person to experience this issue so am hoping someone will come up with a bright idea.

Related

Zend Framework 1 Ajax

Could somebody please suggest me a good beginner tutorial of using Ajax with Zend 1.I have been searching the net for some of this tutorials, but couldn't find an understandable one.In some they say you have to create a .json.phtml file for json response, the others don't.I am very confused about all these ajax calls with Zend Framework 1. Would be very grateful.
Well there really are some basic things.
Get your data (from DB, file, in-code array, whatever)
Get the controller helper
Send the JSON response
And that's it. OK, not exactly but basically yes!
Provided you have the data in $data:
$this->_helper->json($data, true);
will return a JSON response. The documentation is here.
Now there is the other notion of a Context Switch and AjaxContentHelper which:
The ContextSwitch action helper is intended for facilitating returning different response formats on request. The AjaxContext helper is a specialized version of ContextSwitch that facilitates returning responses to XmlHttpRequests.
To enable either one, you must provide hinting in your controller as to what actions can respond to which contexts. If an incoming request indicates a valid context for the given action, the helper will then:
Disable layouts, if enabled.
Set an alternate view suffix, effectively requiring a separate view script for the context.
Send appropriate response headers for the context desired.
Optionally, call specified callbacks to setup the context and/or perform post-processing.
Something like this:
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$contextSwitch->setDefaultContext('json');
$contextSwitch->addActionContext('index', array('xml','json'))->initContext();
$contextSwitch->addActionContext('get', array('xml','json'))->initContext();
$contextSwitch->addActionContext('post', array('xml','json'))->initContext();
$contextSwitch->addActionContext('put', array('xml','json'))->initContext();
$contextSwitch->addActionContext('delete', array('xml','json'))->initContext();
$contextSwitch->addActionContext('head', array('xml','json'))->initContext();
You don't really need a tutorial I think. All you need is a good basic knowledge of how the web works internally and to read the Zend Documentation. Anyway here is some tutorial on ContextSwitch.

Asp.Net Web Api - Change parameter name

In my team we have coding rule that requires that every function's parameter starts with prefix, e.g. *p_someParam*.
With Web Api if we want to request a GET function that takes two parameters, we should add those parameters like "...?p_firstParam=value1&p_secondParam=value2".
Is there some way to use in requests more user-friendly names, like someParam without prefix, that will automatically map to parameters in controller's action? Maybe there is some attribute to rename action parameters? I couldn't find any similar example.
Every clue is appreciated.
I think you looking for URL rewriting, in that you need to map the urls to config or programmatic
http://www.codeproject.com/Articles/2538/URL-Rewriting-with-ASP-NET nice article to follow, its in ASP.Net,

RESTful api for dynamic showform on top of spring mvc

I want to build a typical mvc app for CRUD of simple items, the api s should be RESTful. The catch here is, that i have a large pallete of items that needs to be initialized. On the server side those items are defined as java beans and the corresponding create form for the item is dynamically created from the field information(data type, validation constraints etc) harvested from the bean.
I am new to REST and just read up about how the urls should be nouns defining the resource and action specified by HTTP verb. In that perspective how to model something like
.../client/showForm?type=xyz from non RESTful way to RESTful one ?? My intention here is to tell the server to dynamically construct and send back a CREATE form for client of type xyz. The obvious problem with url i mentioned above is that it specifies action in the url which, from what i have read, makes it non RESTful.
When I think of REST, I think of resources. I think of data. In other words, I don't think of REST as being something that I would typically use to retrieve a form, which is a user interface component.
REST is an architectural style that is used to identify a resource on a server using a uniform resource identifier, or URI. Additionally, actions performed on those resources identified by the URI are determined based on the specific HTTP Method used in the request: GET, POST, PUT, DELETE, etc.
Thus, let's say you have a Client object. That client object might have the following properties:
Name
Location
AccountNumber
If I wanted to retrieve the data for a single client, I might use the following URI:
GET /client/xyz/ # xyx is the accountnumber used to identify the client.
I would use a GET method, since REST describes GET as being the method to use when retrieving data from the server.
The data could theoretically be returned in HTML, since REST is not a standard but more like a series of flexible guidelines; however, to really decouple my data from my user interface, I would choose to use something platform independent like JSON or XML to represent the data.
Next, when adding a client to the collection on the server, I would use the /client/ URI pattern, but I would use the HTTP Method POST, which is used when adding a resource to a collection on the server.
# Pass the data as JSON to the server and tell the server to add the client to the
# collection
POST /client/ {"accountnumber":"abc" , "Name" : "Jones" , "Location" : "Florida"}
If I were to modify an existing record on the server or replace it, I would most likely use the HTTP Method PUT, since REST guidelines say that PUT should be used if repeating the same operation repeatedly would not change the state of the server.
# Replace the client abc with a new resource
PUT /client/abc/ {"accountnumber":"abc" , "Name" : "Bob Jones" , "Location" : "Florida"}
The general idea behind REST is that it is used to identify a resource and then take action on that resource based on what HTTP Method is used.
If you insist on coupling your data with your view, one way accomplish this and retrieve the actual form, with the client data, could be to represent the form as a resource itself:
GET /client/abc/htmlform/
This URL would of course return your client data for client abc, but in an HTML form that would be rendered by the browser.
While my style of coding utilizes data transports such as JSON or XML to abstract and separate my data from my view, you could very well transport that data as HTML. However, the advantage of using JSON or XML is that your RESTful API becomes platform independent. If you ever expand your API to where other developers wish to consume it, they can do so, regardless of what specific platform or programming language they are using. In other words, the API could be used my PHP, Java, C#, Python, Ruby, or Perl developers.
In other words, any language or platform that can make HTTP requests and can send GET, POST, PUT, DELETE requests can be used to extend or build upon your API. This is the true advantage of REST.
For more information on setting up your controllers to use REST with Spring MVC, see this question. Additionally, check out the Spring MVC Documentation for more information.
Also, if you haven't checked out the Wikipedia article on REST, I strongly encourage you to do so. Finally, another good, classic read on REST is How I Explained REST To My Wife. Enjoy.

RESTful URLs: "Impractical" Requests, and Requiring One of Two Request Parameters

I have a RESTful URL that requires either the offset or the prefix request parameter (but not both).
GET /users?offset=0&count=20
GET /users?prefix=J&count=20
What's the best way to enforce this rule? Spring has the #RequestParam annotation with the 'required' property for optional parameters, but I want to enforce an "either-or" rule on these two parameters. I know I could do it in the code, but is there another way to do it?
Also, what's the proper way to handle "impractical" requests? Say I have 100 million users; the following request, although properly RESTful, is not something I want to support:
GET /users <-- Gets all 100 million users, crashes server and browser!
What should I send back?
You can create two methods and choose one of them with #RequestMapping's params attribute:
#RequestMapping(..., params = {"prefix", "!offset"})
public String usersWithPrefix(#RequestParam("prefix") ...) { ... }
#RequestMapping(..., params = {"offset", "!prefix"})
public String usersWithOffset(#RequestParam("offset") ...) { ... }
what's the proper way to handle "impractical" requests?
The lesser-practiced principles of REST include the requirement that resources be "discoverable". If you are asked for a complete list of 800 million users and you don't want to provide it, you might instead consider serving a page that describes in some way how to filter the collection: for example, an XForms document or HTML containing a FORM element with fields for offset/prefix/count, or a URI template with the appropriate parameters
Or you could just send a "413 Entity too large" error - edit: no you can't. Sorry, I misread the description of whath this code is for
If you decide to go down the route of just sending the first page, I think I would send it as an HTTP redirect to /users?offset=0&count=20 so that the client has a better idea they've not got the full collection (and if your response contains a link to access subsequent pages, even better)

Wicket and a rich ajax website: easiest way to do it?

I want to use Wicket to build an application, but I have some designers that would like to write/maintain the javascript, and they basically expect 1 JS-segment per page, and a global JS-file.
I think the most natural way to add javascript in wicket is to add it per component (not per page), which would create problems for those designers (fractioned javascript, and having to write it in java-files). Is there a better way to solve this?
(of course, I expect things to work after a partial refresh.)
And a second (related) thing they'd like (and I'd like actually) is the possibility to request information in JSON-format through a static link , is this possible in Wicket?
I started with JSON by making my wicket pages return the JSON, but quickly realized there are better tools for the job, especially if you will have a full web services layer. If you just need a little JSON here and there, always via a GET, then sure, just make a Wicket page.
I ended up using Jersey with Jackson alongside of Wicket. Jersey simplifies the configuration of URLs that can do different things with different http methods (GET/POST/PUT/DELETE), as well as easily parsing query strings, etc. I'd consider going this route for heavier JSON needs.
You can easily run both Wicket and Jersey in the same web application with a little web.xml configuration.
Wicket's built in AJAX support is always stateful and thus accessed with changing URLs. If your designers aren't planning to use Wicket's JS library, it's pretty straightforward to mount a JSON page:
public class JsonReturningPage extends WebPage {
public JsonReturningPage(PageParameters params) {
String json = "{foo: 4711}";
IRequestTarget t = new StringRequestTarget("application/json", "UTF-8", json);
getRequestCycle().setRequestTarget(t);
}
}
Alternatively, you could also implement your own AbstractRequestTargetUrlCodingStrategy to directly return an IRequestTarget from IRequestTarget decode(RequestParameters params) and mount it in your application.
Regarding JS files, I'd try to educate them to use one file per component. This certainly has the advantage of less copy-paste code and simpler maitenance. Additionally, I'd certainly discourage JS in Java code. It's normally only needed to pass data or config to JS , either as variable definitions or method calls. As this data is typically in Java and JS is written by designers, it's time for designers and programmers to team up.
Quick answer to your second question is yes it is possible. Use bookmarkable links to access a resource that returns JSON data.
You can easily use the following code to dynamically communicate with Wicket:
AbstractDefaultAjaxBehavior callme = new AbstractDefaultAjaxBehavior(){
#Override
protected void respond(AjaxRequestTarget target) {
}
};
page.add(callme);
//From any ajaxrequesttarget you can simply append the following code:
target.appendJavascript("wicketAjaxGet('"+callme.getCallbackUrl()+");");
This way you can have an ajaxlink etc... that will transfer the ajaxrequest to the Wicket side. If you want to pass data (though a static link doesn't sound like that) do the following:
"wicketAjaxGet('"+callme.getCallbackUrl()+"&x='+value_to_pass_back''";
//to Read the value in the respond:
String x = RequestCycle.get().getRequest().getParameter("x");
So the url to the callback is dynamically generated (as the callback url is specific to the session) but it is formed like any other url....
To me this is 10 times simpler than building a JSON system on top of wicket instead of using the one built into it.... I use this all the time and it works great for me at least. If your solution is different/better I would like to know why perhaps.

Resources