I'm new to webapi 2 and trying to get my api to bind to this call below.
Can anyone see what I'm doing wrong?
Call:
https://blabla.azurewebsites.net/myjohndeere/authenticated/e33dd8f74c97474d86c75b00dd28ddf8?oauth_token=1539dccf-d935-4d9e-83be-e00f76cabbb9&oauth_verifier=B22dWL
[RoutePrefix("myjohndeere")]
public class ApiMyJohnDeereController : ApplicationController
{
[HttpGet, Route("authenticated/{callbackId}")]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(ApiResponseModel))]
[SwaggerResponse(HttpStatusCode.InternalServerError, "An unknown error occurred")]
[SwaggerResponse(HttpStatusCode.BadRequest, "Missing FieldMappings")]
public IHttpActionResult Authenticated(string callbackId,[FromUri]string oauth_token, [FromUri]string oauth_verifier)
{
...
}
First of, you missed the 'api' in the route.
Try it like this
https://blabla.azurewebsites.net/api/myjohndeere/authenticated/e33dd8f74c97474d86c75b00dd28ddf8?oauth_token=1539dccf-d935-4d9e-83be-e00f76cabbb9&oauth_verifier=B22dWL
Then, remove the FromUri attribute from your controller method. The attribute is not needed when just reading querystring of value types.
Try it like this
public IHttpActionResult Authenticated(string callbackId, string oauth_token, string oauth_verifier)
The issue was the Azure API gateway was still set to use PUT rather than GET.
Related
My action method returns a view. It looks like the following.
public public ActionResult Init(string additionalParams)
{
Response.AddHeader("additionalParams", additionalParams);
return View(model);
}
The view has a form. The form is submitted to another action method
[HttpPost]
public ActionResult InitPost(MyModel model)
{
string additionalParams = Request.Headers.Get("additionalParams"); <--- getting null
}
how do i get the additionalParams in the post? Please help.
So on the Init(), I was using Route attribute routing, that makes urls look like this http://wwww.example.com/23/22/... Apparently this caused issues with the length of url. So I switched to using query string, by removing the route attribute routing. Now with this url, I can pass my additionalParams just fine, http://www.example.com?id=222&otherID=222&additionalParams="whatever"
Below is WebAPI action. On googling about the below error:-
The requested resource does not support http method 'POST'
I got number of links & updated my api accordingly but still I am getting the same error.
Web api not supporting POST method
ASP.NET Web Api: The requested resource does not support http method 'GET'
[AcceptVerbs("POST")]
[HttpPost]
[Route("rename/{userId}/{type}/{title}/")]
public IHttpActionResult Rename([FromBody] int userId, [FromBody] string type, [FromBody] string title)
{
//my api stuff
}
But still when calling the above via post man throws the error.
How do I get rid of this error??
Also is it possible to fix this without using [FromBody] attribute in the method parameters list?
Any help/suggestion highly appreciated.
Thanks.
You have declared route which requires url parameters
[Route("rename/{userId}/{type}/{title}/")]
So when you send request to api/customer/rename it does not match this method. You should remove parameters which you are passing in request body from route parameters
[Route("rename")]
Make sure that you have appropriate RoutePrefix("api/customer") attribute on your controller.
Second problem is multiple [FromBody] parameters. You will get can't bind multiple parameters error. There is limitation - you can mark only one parameter as FromBody. See Sending Simple Types notes:
Web API reads the request body at most once, so only one parameter of
an action can come from the request body. If you need to get multiple
values from the request body, define a complex type.
You should create complex type which will hold all parameters
public class RenameModel
{
public int UserId { get; set; }
public string Type { get; set; }
public string Title { get; set; }
}
And change method signature to
[HttpPost]
[Route("rename")]
public IHttpActionResult Rename(RenameModel model)
And send request data as application/x-www-form-urlencoded
[Route("rename/{userId}/{type}/{title}/")]
public IHttpActionResult Rename([FromBody] int userId, [FromBody] string type, [FromBody] string title)
The last answer is correct, you're asking for these parameters in the route, but saying that you expect them in the post body. Also, usually the route would begin with a noun rather than a verb. What is it you're renaming? (i.e. [Route("users/rename/{userId}/{type}/{title}")]
Based on your initial post, try this instead:
[HttpPost]
[Route("rename/{userId}/{type}/{title}" Name = "RenameUser"]
public IHttpActionResult Rename(int userId, string type, string title)
{
_myServiceMethod.Rename(userId, type, title);
return new StatusCodeResult(HttpStatusCode.Created, this);
}
Or, if you wanted to do a post with the info in the body:
Declare your data contract:
public class User
{
public string Type { get; set; }
public string Title { get; set; }
}
Then on the endpoint:
[HttpPost]
[Route("rename/{userId}", Name = "RenameUserPost")]
public IHttpActionResult RenameUserPost(int userId, [FromBody] User userData)
{
return new StatusCodeResult(HttpStatusCode.Created, this);
}
Note that in both returns 'this' refers to your controller class that inherits from ApiController. Verified both of these in swagger, and they accept POSTs and return status codes.
Hope this helps.
I had this error for wrong string in Route string on top of my action.
[Route("api/TestReaderPercentStudyHomework/AddOrUpdate")]
I have a client controller that is called "ClientController". The start of the controller is as follows:
[Route("api/[controller]")]
[AllowAnonymous]
public class ClientController : Controller
The first httpget method works like this - naming etc just a "Get":
public IActionResult Get()
{...
..and it does indeed work when I use Postman with a call:
http://localhost:5001/api/Client
However, If I change the name to Index and name it Index like so:
[HttpGet(Name = "Index")]
public IActionResult Index()
{...
return new OkObjectResult(some object)
}
and I use Postman again to call it this time explicitly:
http://localhost:5001/api/Client/Index
I get a 404 status.. - Not found..
I have looked around for some answers on this but its a bit light on for ASPNET Core examples for API and naming conventions..
How do you name an IActionResult API method (via connotations) and call it correctly (eg URL structure)? A little direction on correct convention would be great..
Have you tried this
[HttpGet("Index",Name = "Index")]
public IActionResult Index()
{...
return new OkObjectResult(some object)
}
More detail is given on this link. Please check it out
https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing
I am a newbie to C# am trying to post an array of values to a webapi POST method. Not sure how to go about this. This is what I have so far:
In the controller class:
namespace SATLyncWebService.Controllers
{
[RoutePrefix("lync")]
public class LyncController : ApiController
{
// POST: lync/search/
[HttpPost]
[Route("search")]
public void Post([FromBody]string value)
{
log.Info(value.ToString());
}
}
I get a NullReferenceException on the value field when I send a POST message as follows:
POST http://localhost:55129/lync/search
Application/json
["user1",
"user2 "
]
Thoughts?
I think that's because your signature is taking a single string as opposed to an IEnumerable (or any other sort of collection - List, []...) therefore webapi can't deserialize into that type
I'm trying to use Web API 2 attribute routing to set up a custom API. I've got my route working such that my function gets called, but for some reason I need to pass in my first parameter for everything to work properly. The following are the URLs I want to support:
http://mysite/api/servicename/parameter1
http://mysite/api/servicename/parameter1?parameter2=value2
http://mysite/api/servicename/parameter1?parameter2=value2¶meter3=value3
http://mysite/api/servicename/parameter1?parameter2=value2¶meter3=value3&p4=v4
The last 3 URLs work but the first one says "No action was found on the controller 'controller name' that matches the request."
My controller looks like this:
public class MyServiceController : ApiController
{
[Route("api/servicename/{parameter1}")]
[HttpGet]
public async Task<ReturnType> Get(string parameter1, DateTime? parameter2, string parameter3 = "", string p4 = "")
{
// process
}
}
Web API requires to explicitly set optional values even for nullable types...so you can try setting the following and you should see your 1st request succeed
DateTime? parameter2 = null