asp.net web api controller method taking special parameter - asp.net-web-api

I have an api that takes 2 parameters by querystring :
We call it like this :
mydomain/myapimethod?url=www.toto.com&caller=tata
We receive parameters like this :
[HttpGet]
[Route("myapimethod")]
public HttpResponseMessage Get([FromUri] string url, [FromUri] string caller)
{
//here url: www.toto.com and caller: tata
}
Everything is working well, the problem is when the url parameter is also composed of querystring with several parameters, for example :
mydomain/myapimethod?url=www.toto.com?parama=a&paramb=b&caller=tata
Then in my method :
[HttpGet]
[Route("myapimethod")]
public HttpResponseMessage Get([FromUri] string url, [FromUri] string caller)
{
//here url: www.toto.com?parama=a and caller: tata
// my paramb is removed
// what I would like to do is to obtain :
// url: www.toto.com?parama=a&paramb and caller: tata
}
My url is generatated by javascript.

You must update your url from
mydomain/myapimethod?url=www.toto.com?parama=a&paramb=b&caller=tata
to
mydomain/myapimethod?url=www.toto.com&parama=a&paramb=b&caller=tata
or encode question mark to %3F
mydomain/myapimethod?url=www.toto.com%3Fparama=a&paramb=b&caller=tata

Related

How to map Bootstrap Modal to Spring MVC controller

I have a form in Bootstrap Modal and I want my Spring MVC controller to listen that. My problem is that the modal doesn't generate href because it's inside current page so I can't map just the modal in my Spring MVC controller.
I need it, because I want to show errors from bindingresult object. How can I do this?
This is my modal: http://www.bootply.com/zerZIYpNAF Let's say it's located in index.jsp so imaginary path would be /index#myModal.jsp or something like that.
#RequestMapping(value="/send", method = RequestMethod.GET)
public String get(Dummybean bean){
return "??"; //index#myModal
}
#RequestMapping(value="/send", method = RequestMethod.POST)
public String post(#Valid #ModelAttribute("dummy") DummyBean bean, BindingResult bindingResult){
if(bindingResult.hasErrors()){
return "??"; //index#myModal
}
//do something
}
public class DummyBean{
#NotNull
private String name;
public String getName() {
return username;
}
public void setName(String name) {
this.name = name;
}
You can't directly call the bootstrap modal to pop up by using controller. There for you will not able to bind form with Spring. But you can Achieve it using Ajax. You have to use form like normal Html form without using spring tags.
function searchAjax() {
var data = {}
data["query"] = $("#query").val();
$.ajax({
type : "POST",
contentType : "application/json",
url : "${home}search/api/getSearchResult",
data : JSON.stringify(data),
dataType : 'json',
timeout : 100000,
success : function(data) {
console.log("SUCCESS: ", data);
display(data);
},
error : function(e) {
console.log("ERROR: ", e);
display(e);
},
done : function(e) {
console.log("DONE");
}
});
}
This is an example ajax for you to get an idea. You have to HttpServletRequest to retrieve data from controller side. Above example is taken from http://www.mkyong.com/spring-mvc/spring-4-mvc-ajax-hello-world-example/
1) create new function just for validation
2) create js function using prefer to use jquery and send ajax request to function in step one.
3) depend on validation status will handle errors or send form completely.
please read this article it's fully answered your question
javacodegeeks.com

JObject parameter is null in WebApi Action

I have an api controller action that takes a JObject as a
public class ThemeController : ApiController
{
[HttpGet]
public String Get(String siteName, JObject lessVariables)
{
and an ajax call
$.ajax({
url: '/api/Theme/Get',
data: { lessVariables: JSON.stringify({'brand-primary': '#222222','brand-success': '#222222','brand-danger': '#222222','brand-info': '#222222','btn-primary-color': '#222222'}), siteName: "UnivOfUtah" }
});
When I look at HttpContext.Current.Request.Params["lessVariables"] it gives the correct string of json, but lessVariables is an empty JObject. Is there something else I have to do to setup Json.Net for this?
I've also tried it on a regular controller action
I have a controller action that takes a JObject as a
public class ThemeController : Controller
{
[HttpPost]
public String Post(String siteName, JObject lessVariables)
{
and an ajax call
$.ajax({
url: '/Theme/Post',
data: { lessVariables: JSON.stringify({'brand-primary': '#222222','brand-success': '#222222','brand-danger': '#222222','brand-info': '#222222','btn-primary-color': '#222222'}), siteName: "UnivOfUtah" }
});
same result
The problem is that lessVariables is now a String. The whole structure probably looks like:
{
"lessVariables": "{'brand-primary': '#222222','brand-success': '#222222','brand-danger': '#222222','brand-info': '#222222','btn-primary-color': '#222222'}",
"siteName": "UnivOfUtah"
}
This is why you can see the correct string in the Params, but the framework is not able to convert it to JObject without knowing it is Json. When you Stringify the root object of a request, WebApi is smart enough to take it as Json as a whole, but you stringified a value inside so it has no idea it should be handled as json.
To fix it, you can either do custom binding with a model binder or custom action, or simply change your method to:
[HttpGet]
public String Get(String siteName, String lessVariables)
{
JObject jo = JObject.Parse(lessVariables);
Update:
To make the issue clearer, this is parsed fine by WebApi, but lessVariables is still a string:
[HttpGet]
public String Get(JObject rootObject)
{
// you now have rootObject which has a "siteName" and "lessVariables" parameter
var siteName = rootObject.GetValue("siteName");
var lessVariables = rootObject.GetValue("lessVariables");
// lessVariables.Type would return the JTokenType String

How To Pass formdata parameters into ASP.NET WebAPI without creating a record structure

I have data coming into my form that looks like the image below (sessionsId: 1367,1368).
I've create c# in my webapi controller that works as below. when I've tried ot just make use SessionIds as the parameter (or sessionIds) by saying something like PostChargeForSessions(string SessionIds) either null gets passed in or I get a 404.
What is the proper way to catch a form parameter like in my request without declaring a structure.
(the code below works, but I'm not happy with it)
public class ChargeForSessionRec
{
public string SessionIds { get; set; }
}
[HttpPost]
[ActionName("ChargeForSessions")]
public HttpResponseMessage PostChargeForSessions(ChargeForSessionRec rec)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, new ShirtSizeReturn()
{
Success = true,
//Data = shirtSizeRecs
});
return response;
}
You can declare the action method like this.
public HttpResponseMessage Post(string[] sessionIds) { }
If you don't want to define a class, the above code is the way to go. Having said that, the above code will not work with the request body you have. It must be like this.
=1381&=1380

What is wrong with this ASP.Net and Fiddler example?

I am using Visual Studio 2012 RC. I am using the default routes and have the following Web API controller:
public class FooController : ApiController
{
// GET api/foo
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/foo/5
public string Get(int id)
{
return "value";
}
// POST api/foo
public string Post(string abc)
{
Console.WriteLine("value: {0}", abc);
return "foo" + abc;
}
// PUT api/foo/5
public void Put(int id, string value)
{
}
// DELETE api/foo/5
public void Delete(int id)
{
}
}
I wanted to do a simple test of POST in Fiddler, so I have
Request Headers
User-Agent: Fiddler
Content-Type: application/json
Request Body
{"abc": "def"}
When I debug the request, the parameter abc comes in as null, not "def". Is there something wrong with my Fiddler syntax?
(1) By default, simple types are taken from the URI. To read a simple type from the request body, add the [FromBody] attribute to the parameter.
public string Post([FromBody] string abc)
(2) '{"abc": "def"}' defines an object with a property named "abc" - to send a JSON string, the request body should just be "def"
This answer comes from a link on the ASP.Net Web API site sending-html-form-data , which turns out to be Mike's blog post (I didn't realize that at first). The Web API team has made a few decisions with parameter binding that are quite different from normal MVC controllers.
The correct syntax for sending "simple types" is
public HttpResponseMessage PostSimple([FromBody] string value)
{
// code goes here
And in Fiddler, you put
=def //THIS CANNOT HAVE QUOTES AND = IS MANDATORY
OK, so here are the parts that work very differently from MVC.
You must use [FromBody], as Mike says.
You can only have 1 parameter. If you want more than 1 parameter, you have 2 choices: i) use url query parameters, instead of request body or ii) use a complex object (i.e. your own class).
The request body should be a simple =def and cannot use named parameters.

Polymorphism in action methods MVC

I have two actions:
//Action 1
public FileResult Download(string folder, string fileName) { ... }
//Action 2
public FileResult Download(int id, string fileName) { ... }
When I try to download the following URL:
http://localhost:54630/Downloads/Download/15?fileName=sharedhostinggsg.pdf
The error happens:
The current request for action 'Download' on controller type 'DownloadsController' is ambiguous between the following action methods:
System.Web.Mvc.FileResult Download(Int32) on type SextaIgreja.Web.Controllers.DownloadsController
System.Web.Mvc.FileResult Download(System.String, System.String) on type SextaIgreja.Web.Controllers.DownloadsController
How can I make them:
Url: ../Downloads/Download/15?fileName=sharedhostinggsg.pdf
Action: Action 2
Url: ../Downloads?folder=Documentos$fileName=xx.docx
Action: Action 1
I tried to put a constraint on my route, but did not work:
routes.MapRoute(
"Download", // Route name
"Downloads/Download/{id}", // URL with parameters
new { controller = "Downloads", action = "Download" }, // Parameter defaults
new { id = #"\d+" }
);
Searching the Internet I found several links but I could not understand how I can solve my problem. This, for example, the RequireRequestValue attribute is not found. I do not know which namespace it is.
The RequireRequestValue that you mention is a custom class they created (from Example posted)so you will not find it in any Microsoft namespace.
The class you will see inherits from ActionMethodSelectorAttribute. This attribute class can be used to help filter actions much like the AcceptVerbs attribute. So as in the example of that link they are returning true or false dependant on if a value is specified in the route arguments.
So following from that example you posted, create a class called RequireRequestValueAttribute. Then decorate your two Downloads action methods like so:
[RequireRequestValue("id")]
public FileResult Download(int id, string fileName) { ... }
[RequireRequestValue("folder")]
public FileResult Download(string folder, string fileName) { ... }

Resources