trying to use POST, but API tries to use GET - c#-4.0

I'm trying to get an api method to use POST but it insists on trying to use GET. I've Googled and searched SO, but everything I try just returns the same message.
Here's my controller:
[Route("api/game/{gameId}/createcharacter/{name}")]
[AcceptVerbs("POST")]
[HttpPost]
public IHttpActionResult PostNewCharacter([FromBody]string name)
{
return Created("created", CharacterGenerationService.CreateNewCharacter(name));
}
Here's the message I get no matter what I try:
message: "The requested resource does not support http method 'GET'."
Request
URL:http://localhost:61645/api/game/452/createcharacter/testChar1
Request Method:GET Status Code:405 Method Not Allowed Remote
Address:[::1]:61645
I am using : using System.Web.Http;
Is there a trick to this?
Thanks

use this code:
[Route("api/game/{gameId}/createcharacter/{name}")]
[HttpPost]
public IHttpActionResult PostNewCharacter(string name)
{
return Created("created", CharacterGenerationService.CreateNewCharacter(name));
}

In the route template you said you will get the name parameter value from the URL but in the signature of your method your decorate that same parameter with FromBody attribute which tell that the value will be retrieved from the message body.
You have two choices :
remove the FromBody attribute and your URL will work correctly
or remove the {name} parameter in your route template and post the name value into your request body.
What about the gameId parameter ?
Don't you need it in your method ? If yes, then you need to pass it as a method parameter.

Related

An error that I am unable to fix in android studio

I am creating a app which requires log in and register but while coding for the app I encountered a error (I am noob) can anyone please help with it
Thanks :)
Basic idea is to send the entries to login request page which forwards the details to the php using Json which verifies with the DB but encountering this error any more details if needed please comment so that I can upload and reply.
It's somewhat hard to tell from your question, but it looks like in your Login class, it is looking for an object of type Request<T> in the add() method, but you supplied it with LoginRequest (hence the error message in the second image).
To solve this problem, you need to make your class inherit from a type of Request<T> called StringRequest: you need to have something like this:
public class LoginRequest extends StringRequest {
Without this, the class implicitly chooses Object as it's super class (as all java objects do), which doesn't have the parameters you supplied.
So, where you have the following code:
LoginRequest loginRequest = new LoginRequest(Email_id, Password, responseListener);
RequestQueue queue = Volley.newRequestQueue(Login.this);
queue.add(loginRequest);
RequestQueue's method add() takes a parameter of type Request<T>. LoginRequest is not a Request<T>. This is the reason for your error. LoginRequest needs to inherit from StringRequest. This will fix both errors. If LoginRequest inherits from StringRequest, then it is-a Request<T> and then RequestQueue's method add() can except loginRequest as a parameter.

ASP MVC AttributeRoutes Languagetoken in URL, keep original Url

I'm using attribute routing with asp mvc 5.2.
I want the user to be able to call the urls with a language token like "de" or "en".
mydomain/en/foo
For this I created a routeattribute with a constraint like descriped in this blog post
This works well when the locale part is at the end like:
[LocaleRoute("home/index/{locale}/","de)]
then i could call home/index or home/index/de
But when I move this to the beginning i can't omit the locale any more.
[LocaleRoute("{locale}/home/index","de)]
There i can only call de/home/index but home/index returns a 404 Notfound. Also the constraint isn't called. It looks like the route isn't just found.
Any hints on what i'm doing wrong and what i have to do?
You probably need to specify that the locale is an optional argument :
[LocaleRoute("{locale?}/home/index","de")]
On a side note, are you using different controllers for de & en ? If you use a single controller you don't need LocaleRoute and can use the default attributes (http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx) :
[RouteArea("{locale?}/home/")]
public class HomeController : Controller
{
...
[Route("index")]
public ActionResult Index (string culture)
{
...
}
}
EDIT
You can also register your action with the following additional route as long as you're careful with providing a default value for culture or treating null.
[Route("/home/index")]

Can't pass GET parameter while unit testing Zend Framework 2

I'm having hard time trying to unit test (phpUnit) one of my modules in ZF2. What I'm trying to do is determine whether a classname is present on one of the elements on page when a GET parameter is passed to the controller.
It all works from the browser, however I can't get the GET parameter to be recognized at all when trying to unit test.
This is my code for unit testing:
<?php
namespace ComponentManager\Controller;
use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;
class ComponentManagerControllerTest extends AbstractHttpControllerTestCase
{
public function setUp()
{
$this->setApplicationConfig(
include 'config/application.config.php'
);
parent::setUp();
}
public function testAdminComponentCodeCanBeAccessed()
{
$this->dispatch('/ComponentManager/requestComponent/product/details-1/details-1', 'GET', array('admin' => 1));
// I also tried: $this->dispatch('/ComponentManager/requestComponent/product/details-1/details-1?admin=1');
$this->assertResponseStatusCode(200);
$this->assertMatchedRouteName('ComponentManager/path');
$this->assertControllerName('ComponentManager\Controller\ComponentManager');
$this->assertControllerClass('ComponentManagerController');
$this->assertActionName('requestComponent');
$this->assertModuleName('ComponentManager');
// test will fail here
$this->assertQuery('div.config-active-wrapper');
}
}
The "div.config-active-wrapper" selector works fine when I remove the check for admin parameter presence in GET but when I re-add it, the GET parameter doesn't get recognised at all. Any ideas?
The problem here was that unit testing is a CLI operation and no superglobals are being populated while in CLI. Simple and stupid :P
A solution is to not use superglobals like $_GET here but to pass this "admin" parameter via some ACL and a controller instead.

WebAPI get not converting properly to model binding object

I"m using WebAPI with MVC4, doing a http get that looks like this:
api_version=2&products=[{"id":97497,"name":"iPad"}]&pageno=1
The signature of the get action controller that maps to this call is:
[HttpGet]
public string Get([FromUri] ProductRequest request){ ... }
The problem is that the ProductRequest object passed into the Get action method above contains nulls for products, while all other values are Ok.
So it seems that it has trouble converting products=[{"id":97497,"name":"iPad"}] into the right object type, which is defined as:
public IEnumerable<Products> products { get; set;} in ProductRequest model and Products class looks like:
public int id { get; set; }
public string name { get; set; }
As, an additional information, when using the same call with a POST instead of a GET, it works fine, the object is converted properly.
So, what am I doing wrong, how can I get http GET to properly convert the query parameters to the model passed in?
I think you confused between HTTP POST and HTTP GET that's why you did get the product as null. You could have a look at What's the difference between GET and POST
Basically, I think you could use TempData but it has pros and cons and depend on the context how you use it.
You can do it through the url, but you don't use JSON. Here's what your URL should look like:
api_version=2&products[0].id=97497&products[0].name=iPad&pageno=1
If you wanted to add more products in the same request, you would increment the array index:
{urlasabove}&products[1].id=4234&products[1].name=iPadmini
This is fine for your request, but can quickly get out of hand. For a complex object in a GET request you may consider using a POST instead. Or, you could include the parameters in the GET body but that's not necessarily the best idea. See discussion on this SO question.

parameter in URL jsf2

I need to have this link:
http://myserver:/myproject/innerpage/clip.jsf&id=9099
to extract the id from a code like this:
HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
String clipId = request.getParameter("id");
When I run it on tomcat I get:
message
/OnAir/innerpage/clip.jsf&id=9099
description The requested resource
(/OnAir/innerpage/clip.jsf&id=9099)
is not available.
When I run it without &id=9099 it runs all right.
How can I make it run?
The separator character between path and query string in URL is ?, not &. The & is separator character for multiple parameters in query string, e.g. name1=value1&name2=value2&name3=value3. If you omit the ?, then the query string will be seen as part of path in URL, which will lead to a HTTP 404 page/resource not found error as you encountered.
So, this link should work http://myserver:port/myproject/innerpage/clip.jsf?id=9099
That said, there's a much better way to access the request parameter. Set it as a managed property with a value of #{param.id}.
public class Bean {
#ManagedProperty(value="#{param.id}")
private Long id;
#PostConstruct
public void init() {
System.out.println(id); // 9099 as in your example.
}
// ...
}
The EL #{param.id} returns you the value of request.getParameter("id").
A tip: whenever you need to haul the "raw" Servlet API from under the JSF hoods inside a managed bean, always ask yourself (or here at SO): "Isn't there a JSF-ish way?". Big chance you're unnecessarily overcomplicating things ;)
You first have to show us how you are sending the parameter in your JSF, is it a commandButton/Link? An outputLink? A ? Also are you using redirect=true?
Chances are you are losing the id somewhere during the request.

Resources