How to pass value to httpget ActionResult - asp.net-mvc

The Url bellow i am passing and wanted to receive value from my httpget ActionResult method. I already tested and getting error HTTP Error 404.0 - Not Found. Any idea to correct url or whats the solution?
http://localhost:53081/Dashboard/UpdatePassword/Email=John#gmail.com/Token=809a5bc2-5f1b-ce5b0203ff1b
[HttpGet]
public ActionResult UpdatePassword(string Email, string Token)
{
using (var db = new MyappEntities())
{
return View();
}
}

Parameter are used as query strings unless you setup routing for them in the pattern you want. Therefore your URL should look like
http://localhost:53081/Dashboard/UpdatePassword?Email=John#gmail.com&Token=809a5bc2-5f1b-ce5b0203ff1b

This is an incorrect way to pass the parameters. You need to follow the query string format (notice that # is encoded):
http://localhost:53081/Dashboard/UpdatePassword?Email=John%40gmail.com&Token=809a5bc2-5f1b-ce5b0203ff1b
Another option would be
http://localhost:53081/Dashboard/UpdatePassword/John%40gmail.com/809a5bc2-5f1b-ce5b0203ff1b
but that requires additional setup in your routing config, and frankly looks a bit off.

Updated url, try this:
http://localhost:53081/Dashboard/UpdatePassword?Email=John#gmail.com&Token=809a5bc2-5f1b-ce5b0203ff1b
You can read more about what a querystring is:
https://www.dotnetperls.com/querystring

Related

Why is MVC attribute routing not matching this GUID?

I'm trying to use attribute routing. For various reasons, one of my Guid argments required for a password reset must not be in the queryString so I've had to put it in the path. That itself isn't a problem, except for the fact that I can't get the resetToken to populate in my controller - even when it matches the controller method based on on the Route attribute I have defined.
So given this URL:
http://example.com/Account/ResetPasswordBySMS/96b7ba88-65e0-4dbc-a012-e69545a29a55/?userid=9d394579-afbb-49c4-ba21-877f4dad91fa
...would not populate "resetToken" here? (it's always null)
Change your action to this:
[Route("~/Account/ResetPasswordBySMS/{resetToken?}")]
public ActionResult ResetPasswordBySMS(string resetToken, [FromQuery] string userId, [FromQuery] string code)
{
var guidResetToken= new Guid(resetToken);
}
I tested url http://localhost:55480/Account/ResetPasswordBySMS/96b7ba88-65e0-4dbc-a012-e69545a29a55?userid=9d394579-afbb-49c4-ba21-877f4dad91fa&code=fghjk in Postman. It is working.
And it is not a good idea to mix query string with routing.I would add userId and code to routing too:
[Route("~/Account/ResetPasswordBySMS/{resetToken?}/{userId?}/{code?}
public ActionResult ResetPasswordBySMS(string resetToken, string userId, string code)
I can see the url error - slash after reset token and before ? mark. This slash should be gone.

Query String from BeginForm in MVC 3

I want to use BegingForm with Get method and this is what I do
#using (Html.BeginForm("Search","Home",FormMethod.Get))
{
//My input elements
}
public class HomeController : Controller
{
public ActionResult Search(string queryString)
{
}
}
but query string always comes back as null. I think, I need to do something with route but no luck
routes.MapRoute(
"SearchRoute", // Route name
"Home/Search{queryString}", // URL with parameters
new { controller = "Home", action = "Search", filter = UrlParameter.Optional } // Parameter defaults
);
Obviously, the coming url to the server is something like
Home/Search?query="blah"&query2="blah"&query3="blah"
What am I doing wrong? What is the correct way to get the query parameters in my controller when I want to use get with beginform?
Also, what if the content of my BeginForm can change and so the query string parameter names could be different depending on the rendered page but I want one Search method that analyze the query string and do the right thing?
Also, is a way for them to query parameters to come in a dictionary?
Obviously, the coming url to the server is something like
Home/Search?query="blah"&query2="blah"&query3="blah"
That's how HTML <form> with method GET works and this has nothing to do with ASP.NET MVC, it's plain HTML. You can't do much about it other than having your controller action look like this:
public ActionResult Search(SearchViewModel model)
{
...
}
Where SearchViewModel will contain properties for each input field on this form. Also you don't need this SearchRoute as it won't work that way.
This being said you could probably use javascript in order to subscribe for the onsubmit event of the form, cancel the default submission (which exhibits the behavior you are observing currently), manually fetch all the values inside your form and then manually generate the url you want and redirect to it using window.location.href = '....';. I am mentioning this only for completeness but absolutely not as something that I recommend or that you should ever do.
If you want to get the items from the query string, just use the "Request" object from the ControllerBase:
public ActionResult Search()
{
var queries = new List<string>();
foreach (var parameter in Request.QueryString)
{
queries.Add(parameter.ToString());
}
//Do Stuff with the query parameters...
return View("Index");
}
And "Request.QueryString" is a dictionary just as you wanted :)

How to route legacy QueryString parameters in ASP.Net MVC 3?

I am using a third party service that does an async callback to a URL I provide to them.
So I tell them to use http://www.mysite.com/Status/Incoming.
This must obviously map to an Incoming() method on my StatusController.
However, what I don't have control over is the format of the parameters they call my URL with.
E.g. They will do a callback such as: http://www.mysite.com/Status/Incoming?param1=val1&param2=val2&param3=val3
I want to map this to the parameters of my action method: Incoming(string param1, string param2, int param3)
How do I do this?
I have found a lot of stuff about custom routing, but nothing about legacy QueryString parameters.
There is no such thing as legacy query string parameters. There are query string parameters and they are part of the HTTP specification. And assuming that the http://www.mysite.com/Status/Incoming?param1=val1&param2=val2&param3=val3 url is called you don't need any route to make it map to the following action (the default route will do just fine):
public ActionResult Incoming(string param1, string param2, string param3)
{
...
}
The default model will take care of binding those values.
Why not use a catch all?
routes.MapRoute(
"Incoming",
"Status/Incoming/{*path}", // URL with parameters
new { controller = "Status", action = "Incoming"}
);
then in your controller,
public ActionResult Incoming(string path){
// the next line would probably be better off in a model binder, but this works:
var dictionary = path
.Substring(path.IndexOf("?")+1)
.Split("&")
.Select(x =>
{
var kvArray = x.Split("=");
return new KeyValuePair<string, string>(kvArray[0], kvArray[1]);
})
.ToDictionary(x=>x.Key,x=>x.Value);
return Incoming(dictionary);
}
public ActionResult Incoming(Dictionary<string,string> dictionary){
//do stuff
}
All that being said, I think using the Request.QueryString is probably a better approach. As long as you are using MVC, it is accessible from your controller. However, if you can guarantee that the correct parameters will be passed then Darin's approach is going to be the best choice.
When I've had to deal with this before now, I just use the "legacy" call of Request.QueryString. It still works, even if it isn't very graceful.

Get header values in ASP.NET MVC

I have a requirement to capture the HTTP User Agent header coming in from a device, take the value and remove a 'uuid' This UUID can then be used to direct the device to the correct location to give it the files relevant to the device.
In webforms I was able to get it using
Request.ServerVariables["HTTP_USER_AGENT"]; //inside of Page_Load method
How would I go about this in MVC?
if in controller, you can easily get the header by this:
Request.Headers.GetValues("XXX");
if the name does not exist, it will throw an exception.
You do it the same way, in the controller:
Request.ServerVariables.Get("HTTP_USER_AGENT");
The Request object is part of ASP.NET, MVC or not.
See this for example.
It should be in the Request.Headers dictionary.
.Net 6 and above, this is how it works:
Request.Headers.TryGetValue("Auth-Token", out StringValues headerValues);
string jsonWebToken = headerValues.FirstOrDefault();
I prefer the new syntax which is more concise:
[HttpGet]
public async Task<IActionResult> GetAuth(FromHeader(Name = "Auth-Token")] string jwt) {
Headers without hypens -'s don't need the Name, they map automagically:
[HttpGet]
public async Task<IActionResult> GetAuth([FromHeader]string host) {
If there is anyone like me, who Googled to see how to get the Content-Type HTTP request header specifically, it's fairly easy:
Request.ContentType
With Core 3.1 and Microsoft.AspNetCore.Mvc.Razor 3.1, you can:
string sid = Request.Headers["SID"];
For whatever header variable you are looking for. Returns NULL if not found.

ASP.NET MVC Preview 5 routing ambiguity

I have a problem with a sample routing with the preview 5 of asp.net mvc.
In the AccountController I have 2 actions:
public ActionResult Delete()
public ActionResult Delete(string username)
While trying to look for Account/Delete or Account/Delete?username=davide the ControllerActionInvoker throws a exception saying that Delete request is ambiguous between my tow actions methods.
The default route in the global.asax hasn't been changed.
Shouldn't the action invoker understand what's the method to call looking in the parameters list?
Using the preview 4 I hadn't these kind of problem performing the same operation.
Any idea?
Solution found!
With the introduction of the ActionNameAttribute, it's now necessary to filter manually which method to call depending on the request. This is done by the ActionSelectionAttribute.
Full explanation here: http://haacked.com/archive/2008/08/29/how-a-method-becomes-an-action.aspx
I can't say for sure why this is happening. But you might want to consider only having the Delete(string username) action and removing the parameter-less overload.
Because string is nullable my understanding is that simply calling Account/Delete will invoke the action with a null username parameter which you can then test for at the beginning of the action method.
What I'd do is ditch the blank Delete(), and only use Delete(string username)
In your url routing you'd have something similar to "/{Controller}/{Action}/{username}/" ?
If you have "/{Controller}/{Action}/{Id}/" you'd be better off doing Delete(string id) and that way just using the url to handle this "/Account/Delete/davide/"
That said use your default route which should be something like the default Id is ""
Then in your Delete(string id) method have:
public ActionResult Delete(string id)
{
if(string.IsNullOrEmpty(id)) return EmptyID();
// Continue normal Delete method
}
public ActionResult EmptyID()
{
// The method you were going to have on a blank delete.
}
That or just wrap it up in the one method on an if {} else {}
Either way I'd just be going with the one method and doing a default on your username/id in your route of an empty string and handle it that way.
If you want to contact me on further follow up to what I mean, or whatever will help, ping me at andrew# my domain on my info page.
Edit: Ah pretty much what Berko said anyway, I'm not sure how Named Attributes would help - so please post a comment here detailing it for other guys who find the same issues! :)
Its ambiguous because the two controller action are the same post method..
You can only used that in form posting scenario for example you are submitting a form data that uses HTTP post..

Resources