How to send null value to Web API endpoint - asp.net-web-api

I have an endpoint like the following. The signature allows id2 to be null. If I call this endpoint from Postman or a front end application and omit id2 I get a 404 not found error. How could I execute the endpoint without passing a value for id2 and not get a 404?
[HttpGet("{id1}/item/{id2}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<List<myModel>>> GetItems([FromRoute] long id1, [FromRoute] long? id2)
{
return Ok(await myService.GetItemsAsync(orderId, orderItemId.Value));
}

Related

Null value parameters not hitting on Web api contoller

This api contoller hit only when first two parameter is non nullable, if both datetime parameter is null,then it is not hitting ,I getting a 404 error , please give a solution
[HttpGet("userReports/{empid:int}/{sdate:DateTime?}/{edate:DateTime?}")]
public IEnumerable<object> usersReport(int empid,DateTime? sDate, DateTime? edate)
{
return employeeDailyStatusService.GetUserReport(empid, sDate, edate);
}
I'm using this url for testing in postman
https://localhost:44308/api/EmployeeDailyStatus/userReports/14/null/null
Any routing will translate you url
https://localhost:44308/api/EmployeeDailyStatus/userReports/14/null/null
as this
https://localhost:44308/api/EmployeeDailyStatus/userReports/14/"null"/"null"
null will be just a string "null".
You just need this url:
https://localhost:44308/api/EmployeeDailyStatus/userReports/14

Invoking the web api get method with multiple parameters returns 404 not found error

I have written the following HttpGet method and calling it with 2 parameters. When I try invoking it via postman , I get 404
not found error. Not sure what the problem is in my call
[HttpGet]
[AllowAnonymous]
[Route("unique-email/{clientCompanyId:int}/{email}")]
public IActionResult UniqueEmail( int clientCompanyId, string email )
{
_identityService.CheckUniqueEmail(clientCompanyId, email );
return Ok();
}
I tried the following ways to invoke it
http://localhost:57973/unique-email?clientCompanyId=29&email=test#test.co.uk
http://localhost:57973/unique-email?clientCompanyId=29&email="test#test.co.uk"
http://localhost:57973/unique-email?clientCompanyId=29&email='test#test.co.uk'
Code
public bool CheckUniqueEmail(int clientCompanyId, string email)
{
return _userUow.UniqueEmail(clientCompanyId, email);
}
public bool UniqueEmail(int clientCompanyId, string email)
{
bool anyMatching = ClientCompanyContactRepository.Get()
.Any(x => x.Email == email && x.ClientCompanyId == clientCompanyId);
return !anyMatching;
}
First, check if you have a Route attribute on controller or set any url prefix like api somewhere.
Your urls doesn't meets the requirement path
/unique-email?clientCompanyId=29&email=test#test.co.uk
because route attribute is
[Route("unique-email/{clientCompanyId:int}/{email}")]
it means that url should be
/unique-email/29/test#test.co.uk
If you need to pass parameters as a query string then use [FromQuery] attribute
The route you use in the controller is incorrect with the route you specify in the postman.
your Route
[Route("unique-email/{clientCompanyId:int}/{email}")]
And Uses
http://localhost:57973/unique-email?clientCompanyId=29&email=test#test.co.uk
http://localhost:57973/unique-email?clientCompanyId=29&email="test#test.co.uk"
http://localhost:57973/unique-email?clientCompanyId=29&email='test#test.co.uk'
With this route you used in the code you can use it in the postman
http://localhost:57973/unique-email/29/test#test.co.uk
But if you want to route your route as you did in the postman you first built, make a change to your code.
[HttpGet]
[AllowAnonymous]
[Route("unique-email")]
public IActionResult UniqueEmail([FromQuery] int clientCompanyId, [FromQuery] string email )
{
_identityService.CheckUniqueEmail(clientCompanyId, email );
return Ok();
}
And Postman
http://localhost:57973/unique-email?clientCompanyId=29&email="test#test.co.uk"

Sending array of string from postman client

I am using web api with identity 2.0.
I want to assign multiple roles to a user.
I am using post man client to communicate with web api.
In api the method i used to get user id and roles for the user is given below:
public async Task<IHttpActionResult> AddRoleToUser(string userid,[FromUri] string[] selectedRoles)
Here selectedRoles is an array.
From postman client i am passing array as given below :
I am passing user id in the url.
Am i passing the array of roles in correct format from postman client?
The call to api was success ,but selectedRoles always contains null value.
I tried with raw json as given below,but it did not worked
If i can pass the roles as raw json,can any show an example
First problem: you're specifying that selectedRoles array comes from the URI (URL) with this attribute: [FromUri]. You need to remove this attribute, because you're sending it in the request body, not in the URL.
Web API actions can only receive a single parameter from the request body, and any number of parameters from the URL. So you need to pass the userid parameter as a query string parameter, like this ?userid=123123, and the other parameter in the body. (You could also create a route that includes a userid, or receive the userid as the id parameter and pass it as an URL segment, if you're using the deafult route)
You also need to specify in your headers the format of the information you're sending in the body. So you need to include this header: Content-Type: application/json, because you're including JSON in your request body.
Finally, as you're sending a single parameter from the body, you can send it like this:
['Admin', 'Employee']
If you want to use the format in your example, you shuould create a class to use as parameter in your action, that would look like this:
public class RoleList
{
public string[] selectedRoles { get; set; }
}
And your action should include this as parameter:
public async Task<IHttpActionResult>
AddRoleToUser(string userid, RoleList roleList)
method code in C#:
public void Put([FromBody]string[] selectedRoles)
{
foreach (var role in selectedRoles)
{
}
}
to call method in postman
in heading tab add your parameter and Content-type parameter with value application/x-www-form-urlencoded
in body tab select raw and JSON(application/json)
then in body box add your array like below:
['Admin', 'Employee']

Web API 2 attribute routing returning 404

I'm having trouble getting the Web API 2 attribute routing to work.
I've been trying everything I could find this whole evening but I can't find the problem.
What I want to achieve is the following:
Make a POST request to http://localhost:xxxx/api/chat/joingroup/1234 to get to the following API call:
[Route("joingroup/{id}")]
[HttpPost]
public async Task<IHttpActionResult> JoinGroup(string id, string connectionID)
{
await hubContext.Groups.Add(connectionID, id);
return Ok(hubContext.Groups.ToString());
}
This keeps getting me a http 400 message.
{"message":"No HTTP resource was found that matches the request URI 'http://localhost:41021/api/chat/joingroup/123'.",
"messageDetail":"No action was found on the controller 'Chat' that matches the request."}
But sending a post to: http://localhost:41021/api/chat/sendmessage/pm/123123 and also to http://localhost:41021/api/chat/joingroup gives me a 200
The chatcontroller:
[RoutePrefix("api/chat")]
public class ChatController : ApiController
{
IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
[...]
[Route("joingroup/{id}")]
[HttpPost]
public async Task<IHttpActionResult> JoinGroup(string id, string connectionID)
{
await hubContext.Groups.Add(connectionID, id);
return Ok(hubContext.Groups.ToString());
}
HTTP POSTS to http://localhost:xxxx/api/chat/sendmessage are working fine.
I cannot figure out why it isn't going to the correct method when I'm calling a POST on http://localhost:xxxx/api/chat/joingroup/1234.
SOLUTION:
The solution was to reference both values that are needed in the JoinGroup method, id and connectionID. Now the request will hit this method.
Using:
http://localhost:xxxx/api/chat/joingroup/john?connectionid=123 will work.
I noticed two things on the code you sent through:
the path you POST to is: localhost:xxxx/joingroup/1234 , this
should be localhost:xxxx/api/chat/joingroup/1234
because you have 2 parameters for the joingroup, you will need to pass both of them through, may be like this localhost:xxxx/api/chat/joingroup/1234?connectionID=value or you can pass it on the request body
if the connectionID is optional you can modify the method to use option al parameters like this
public string JoinGroup(string id, string connectionID = "")
please let me know if this helps.
Thanks
Ashraf
I assume the connectionID parameter references the POSTed data. The easiest thing to make it work is to decorate it with the [FromBody] attribute and put an = in front of the value being sent like this: =MyConnection1.
Web API expects an object with properties or an array otherwise. Alternatively, you can wrap the connection ID with a custom class and pass it serialized as JSON/XML.

How to pass parameters on POST requests on Spring-MVC controller method

I am using Spring MVC.
I am sending a POST request from an Ajax context and I sent one parameter. The Content-Type of the request is {'Content-Type':'application/json;'} and in Firefox's Firebug I see the post request is sent with one parameter:
JSON
orderId "1"
Source
{"orderId":"1"}
How can I get it in my controller in the server? The signature of my method is:
#ResponseBody
#RequestMapping(value = "/blahblah", method = RequestMethod.POST)
public void blahblah(#RequestBody(required=false) String orderId ){...
The incoming orderId is always null. Any ideas?
Thanks..
UPDATED: I used {'Content-Type':'application/x-www-form-urlencoded;'} and send my parameters in the following format "orderId=" + id . Also, I changed the server method using #RequestParam String orderId and the value is passed.
I used {'Content-Type':'application/x-www-form-urlencoded;'} and send my parameters in the following format "orderId=" + id .
I changed also the server method using #RequestParam String orderId and the value is passed.

Resources