i have this order controller and the method below.
how can i call this method from java?
the link is also available online under: http://www.life-projects.com/api/orders
public class OrdersController : ApiController
{
[HttpPost]
public String Add(String order)
{
return "test string";
}
}
this is the code that tries to access the method
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.life-projects.com/api/orders");
httppost.setEntity(new StringEntity(Order_Data));
HttpResponse resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();
someone tries to call the post method and it doesn't work.
why?
thanks,
Related
I am new to Web API and I have question that can not resolve.
This is my question: how call a Web API that need multiple parameters (stream or object and two or three string)? And how handle this parameters inside Web API?
For example, I have this method in my Web API:
public class MyController : ApiController
{
[HttpPost]
public MyObject Method(Stream s, string first, string second)
{
// take the parameters and do something
}
}
Where Stream is a stream of file (or an object in other cases).
How can add all these parameters to client request body? And how take them from there and use in the method?
EDIT:
this solution is good?
Here the client:
{
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
queryString["first"] = "true";
queryString["second"] = "false";
var uri = "https://myapi.com/api/mycontroller/method?" + queryString;
HttpResponseMessage response;
byte[] byteData = Encoding.UTF8.GetBytes(myFile);
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("<application/json >");
response = await client.PostAsync(uri, content);
}
}
And here the Web API:
[HttpPost]
public MyObject Method([FromBody]Stream s, [FromUri]string first, [FromUri]string second)
{
//do something
}
WebApi does not support to passing multiple parameter in this way, simply you can create a dto/model class and pass that class from body to the method.
public class Foo
{
public Byte[] s {get;set;}
public string first {get;set;}
public string second {get;set;}
}
WepApi controller:
public HttpResponseMessage Register([FromBody] Foo foo)
{
//do something
return Ok();
}
Update:
If you don't want to create classes for your each methods. Then you can use like following one, but recommend to use first one.
public HttpResponseMessage Register([FromBody]dynamic value)
{
//convert to attribute
string first = value.first.ToString();
string second = value.second.ToString();
}
Here is good read: Getting Started with ASP.NET Web API 2 (C#)
This question already has an answer here:
Simple post to Web Api
(1 answer)
Closed 6 years ago.
I am attempting to send a string to my web api like this:
public IList<Product> GetProducts(string myString)
{
IList<Product> retVal = null;
using (var client = GetClient())
{
HttpContent httpContent = new StringContent(myString, Encoding.UTF8, "application/json");
// HTTP POST
HttpResponseMessage response = client.PostAsync("api/products", httpContent).Result;
}
return retVal;
}
In my ProductsController my action method looks like this:
// POST: api/products/filter
[HttpPost("filter")]
public IList<Product> Filter(string filter)
{
}
For some reason the filter param keeps coming in as null. Any ideas why?
You should decorate parameter with [FromBody] attribute as post will not take value from url I suspect
Looks like youre posting to api/products, not api/products/filter.
Signature for the method should be as Vidas says with the from body attribute, but posted to the correct url.
[HttpPost]
[Route("api/products/filter")
Public ilist<product> Filter([FromBody] string filter)
{...}
While the route isnt specifically necessary, it can help you specify the url you are working with!
From MVC controller calling Web API post method returns the below error:
"The remote server returned an error: (405) Method Not Allowed"
Below MVC controller Action code calls a helper class method and while debugging I can see control moves from here to next method:
public ActionResult Submit(FormCollection form)
{
Lead_Options lead = new Lead_Options();
lead.Situation = form.GetValue("InsuranceFor").AttemptedValue;
lead.State = form.GetValue("InsuranceState").AttemptedValue;
Uri url= Url_Helper.GetUri(BaseUrl, service1+"Post"); // returns http://localhost:52985/api/HealthInsurance/Post
string obj= new JavaScriptSerializer().Serialize(lead);
Object data = WebApi_Helper.PostData(url,obj);
return RedirectToAction("Parameters");
}
"WebApi_Helper.PostData" is Helper class, a generic method to be sued to call web api:
public static string PostData(Uri url,string obj)
{
string data = null;
try
{
using (WebClient proxy = new WebClient())
{
proxy.Headers.Add(HttpRequestHeader.Accept, "application/json");
data = proxy.UploadString(url,"Post", obj); //Here got error
}
}
catch (Exception ex)
{
throw ex;
}
return data;
}
Below is WebAPI Method code but while debugging request do not come here at all
[HttpPost]
public void Post(string lead)
{
//leadOptService.AddListOptions(lead);
}
Please direct me what wrong I m doing and how it can be resolved.
HTTP methods are case sensitive. Try with:
data = proxy.UploadString(url,"POST", obj);
or
data = proxy.UploadString(url, obj); // this overloads POSTs the data
Also, the HttpPost attribute is redundant since Web Api, by convention will only allow POST for public void Post(string lead).
And as a good practice, the Post should return a value. At the very very minimum, an HttpResponseMessage with status code 201 (for success) or 500 (for errors) and othe rcodes as applicable.
I have an MVC API controller with the following action.
I don't understand how to read the actual data/body of the Message?
[HttpPost]
public void Confirmation(HttpRequestMessage request)
{
var content = request.Content;
}
From this answer:
[HttpPost]
public void Confirmation(HttpRequestMessage request)
{
var content = request.Content;
string jsonContent = content.ReadAsStringAsync().Result;
}
Note: As seen in the comments, this code could cause a deadlock and should not be used. See this blog post for more detail.
using System.IO;
string requestFromPost;
using( StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream) )
{
reader.BaseStream.Position = 0;
requestFromPost = reader.ReadToEnd();
}
I suggest that you should not do it like this.
Action methods should be designed to be easily unit-tested. In this case, you should not access data directly from the request, because if you do it like this, when you want to unit test this code you have to construct a HttpRequestMessage.
You should do it like this to let MVC do all the model binding for you:
[HttpPost]
public void Confirmation(YOURDTO yourobj)//assume that you define YOURDTO elsewhere
{
//your logic to process input parameters.
}
In case you do want to access the request. You just access the Request property of the controller (not through parameters). Like this:
[HttpPost]
public void Confirmation()
{
var content = Request.Content.ReadAsStringAsync().Result;
}
In MVC, the Request property is actually a wrapper around .NET HttpRequest and inherit from a base class. When you need to unit test, you could also mock this object.
In case you want to cast to a class and not just a string:
YourClass model = await request.Content.ReadAsAsync<YourClass>();
I'm working on an MVC4 project that has site controllers and API controllers. How do I send a request to an API controller from one of the site controllers?
For example, I might have an APiController that looks like this:
public class FooController : ApiController {
[HttpGet]
public int Add(int a, int b) {
return a + b;
}
}
How would I send a request to /FooController/Add?a=1;b=2 from this Controller?
public class BarController : Controller {
[HttpGet]
public int AddOneAndTwo() {
//What goes here?
}
}
EDIT: What I really wanted to do was call methods from my ApiController class from my site Controller, and I assumed I had to conjure some MVC4 magic to make it work. As per the comments between Felix and me, I can just create an instance of my ApiController in my site Controller and go from there. But if you still need to access ApiController methods via HTTP, then boy howdy, is Felix's answer to my original question for you.
The code with restsharp would be something like this:
protected IRestResponse GetResponse(int a, int b)
{
var client = new RestClient
{
BaseUrl = "http://localhost:8888/api/FooController"
};
var request = new RestRequest
{
DateFormat = DataFormat.Xml.ToString(),
Resource = "Add",
Method = Method.GET
};
request.AddParameter("application/json",
JsonSerializer.JsonSerialize(new {a, b}),
ParameterType.RequestBody);
return client.Execute(request);
}