asp.net webapi mapping a string param that has a querystring - asp.net

I need to map a string param with a webapi method. Something easy:
/api/mycontroller/this_is_my_input_param
I know how to do it and it's working fine. However, problem is that my input param can have a query string. Something like:
/api/mycontroller/term?p=1&n=value
and I want that webapi map the entire "term?p=1&n=value" with the input param in the method. I just wanna tell webapi "ey, just take all the string you have after /api/mycontroller/ and send it to the action as input parameter"
I know that probably is not the best architectural thing, but I need it that way. Also, I don't know how many params and names I can have, so I can't use a complex type. I also need it as a GET. I know how to do it with a POST, but I need a GET if it's possible.
Many thanks.

Can you able to add that querystring to body and then by using (frombody/ fromuri) attributes
to grab the querystring and do whatever you want
Route[api/mycontroller/term]
public HttpResponseMessage myController([fromBody] querystring)
{
// do something for that querystring
}
please check webapi attributes from this link
enter link description here

Finally what I'm doing is mapping the entire HttpRequest, that way I can work with the full requestted URL and get all that I have after the Controller name:
public async Task<string> Get(HttpRequestMessage request)
I know would be better to create a custom ModelBinder or something like that, but in my case is enough doing it that way.
thanks for your help.

Related

How to add query string parameters to GetFromJsonAsync in a Blazor app?

I'd like to add some query string parameters to the GetFromJsonAsync helper method from the 'System.Net.Http.Json.HttpClientJsonExtensions' library. Reading through the docs and examples, it seems like this helper is more for vanilla API calls that do not provide a lot of intervening for custom headers or parameters, but I don't have clarity on this. It appears to add custom parameters or headers, the preferred method is to use the more raw, HttpClient.GetAsync Method.
I suppose I can just string manipulate the requestUri parameter of GetFromJsonAsync but I'm not seeing this as a mainstream practice. I just want to add some simple query string parameters like the following:
'zip': 90210
'units': 'imperial'
What is the correct or mainstream way to manipulate the Http call to an API for parameters or headers in a Blazor application?
I found this works
var data = await Http.GetFromJsonAsync<MenuApiModel>($"{nameof(Menu)}?menuId=1");
Notice I simply put the query param in the url itself.
I hope that helps.

How to send list as parameter for search in angular service to .net core

Please Help me I need to retrieve a list of details using a list of parameters. How to achieve that from angular 10 and .net Core?
Also, Single Entries is working for search. But If I try to enter a second entry in the input field and tried to search it is not working.
The method name is GetPodForwardings.
This is the Method in angular (Service)
GetPodForwardings(conNo,newPage,pageSize)
{
return this.http.get(`${this.BaseUrl}Pod/GetConsignmentList?conNo=${conNo}&newPage=${newPage}&pageSize=${pageSize}`)
}
In .NET Controller
[Microsoft.AspNetCore.Mvc.Route("GetConsignmentList")]
[HttpGet]
public async Task<IActionResult> GetListofConsignments([FromQuery]List<long> conNo,int currentPage,int pageSize)
{
return await ProcessQuery(new GetListofConsignmentByConsignmentNoQuery(conNo,currentPage,pageSize));
}
The proper way of adding parameters to an url in Angular is to use the second options parameter of the http.get("url",options) function. Unfortunatly they don't accept arrays rightaway (there is an open github issue).
However string interpolation like you did should also work. You seem to just have the wrong format. As this is treated very framework specific look at this answer to get the right format for your case.

Removing null/empty keys from a query string in asp.net MVC

Is there a way I can remove null or empty keys from a query string in asp.net MVC? For example I have a page where I filter data on a results table, if I search for John the query string would be redisplayed as:
candidates?FirstName=John&LastName=&Credit=false&Previous=false&Education=&Progress=
and not
candidates?FirstName=John
I looked at URL routing but I wasn't sure if it was something that should be used for cosmetic things like this or if it is possible to achieve what I'm asking using it.
How are you generating that URL? With Routing, if those are meant to be in the query string, it should work fine. We only generate query string parameters for RouteValues that you specify.
One thing I've done in the past is to write my own helper method for specific links where I might pass in an object for route values, but want to clear out the values that I don't need before passing it to the underlying routing API. That worked well for me.
Whatever URL generator, or control you are using would need special logic to strip these unwanted tags from the list. It's not obvious to a generic URL generator or control that Credit=false is useless -- couldn't it be Credit=true is the default? Similarly an empty string can mean something. (Also, Lastname= is different from Lastname.
I sometimes need to work on my route values in partials that are used by variuos views.
Then I usualy access the routeDictionary and change it. The benefit you get is, that there is a good chance that the code will survive changes in the routing and that you can use routeValues in multiple generated URL.
Most people would argue that the best place for this code is not the view. But hopefully you get the idea.
The view code:
RouteValueDictionary routeValues = ViewContext.RouteData.Values;
routeValues.Remove(...);
routeValues.Add(...);
routeValues["Key"] = ...;
<%
using (Html.BeginForm(
Url.RequestContext.RouteData.GetRequiredString("Action"),
Url.RequestContext.RouteData.GetRequiredString("Controller"),
routeValues,
FormMethod.Get))
{ %>
Maybe use this Querystring Builder - iterate querystrings in the Request.QueryString dictionary and build a new one using the builder (or just string-concat them)?

How to create a simple ASP.NET MVC action method that accepts HTTP-POST data?

i wish to have a simple Action in my controller that accepts a few optional values and some integer values.
this is my route i wish to have:
HTTP.POST
/review/create
and this is the Action method i would like...
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult Create(int userId,
int addressId,
byte baseScore,
byte reviewType,
string subject,
string description)
{ ... }
I'm under the uneducated impression that all of those arguments above will be populated by the forms collection values ... but it's not happening. Also, I have no idea how I would write a route, to handle those ... because those values are form post data....
here's my global.asax....
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Api - Search methods.
routes.MapRoute(
"Search Methods",
"{controller}/{action}"
);
In fact, the action method is never called because it doesn't seem to find it :(
But, if create and action without any of those arguments, then it finds it ?????????
How would you write a route and action method to accept some require and some optional arguments, for the route /review/create ?
As far as i can see you may rewrite your controller action like this:
public ActionResult Create(int foo, int bar, byte blah, string name, int? xxx) {
// code here
}
The ModelBinder will then ensure that foo,bar and blah are set. Name and xxx may be null. I can't test it a the moment, but i think return type of the action should be ActionResult.
If you are POST'ing a form, just make sure that the elements in your form (textboxes, checkboxes, textarea, etc) have id's that match the parameters in your method. As an alternative you can pass a FormCollection to the method, and do myFormCollection["foo"] to get a string representation of the value (which can then be parsed to an int).
From my experience, you are missing a number of key elements and concepts with this question.
First and foremost, I don't believe you can execute a POST without a form. The form has to contain the controls from which you pull the values that get passed to the controller method. If the goal is to simply unit test your POST controller method, then just call the method directly in your test, which it appears that you're doing, based on one of your comments. If you involve the view, then you're doing integration testing, not unit testing. Regardless of the test type, the test will always fail because you are choosing not to build the form. Even if you manage to force the POST using Fiddler, Firebug or any other mechanism, you're still not testing the view, you're testing the HTTP protocol.
I highly recommend that you employ a web application testing tool, such as WatiN or Selenium, to test your web pages, rather than throw together a quick-and-dirty test that really doesn't test anything useful.
In your post request set content-type="application/json; charset=UTF-8" and pass the values for the method parameter in JSON format. This should make Asp.MVC not to look in FormCollection for those values.

Getting to the query string (GET request array) inside a web service in .NET

I'm looking to find a way to access the .net query string contained in the standard ASP.NET request object inside a web service. In other words if I set a SOAP web service to this url:
http://localhost/service.asmx?id=2
Can I access the ID Get variable?
I just looked for "Request" of the context in asmx file and I saw that. But I'm not sure if it is right.
this.Context.Request.QueryString["id"];
HttpContext.Current.Request.QueryString["id"]
Since you ask, I guess there is no HttpContext.Current.Request ?
While searching for the solution of the same problem i decided to take different approach.
My query string was packed with lots of variables and since I was not able to access query string data from the web service, and I also did not want to send each query string variable as a separate parameter, I prepared my web method to expect one aditional string parameter.
That parameter was window.location (entire url of the page) in my javascript function on .aspx page
Once I had url in my web service, the rest was quite stright forward
Uri myRef = new Uri(stringMyWindowLocationParameter);
System.Collections.Specialized.NameValueCollection mojQuery = HttpUtility.ParseQueryString(myRef.Query);
Now my query string is contained inside myRef object and this is how I call it
// Instead trying to request query string like this
string myId = HttpContext.Current.Request.QueryString["id"];
// ... I called it like this
string myId = myRef["id"];
Maybe it's not the most elegant way but it solved my problem.

Resources