Having trouble with IUrlHelper - c#

I have a method like so:
[HttpPost]
public async Task<IActionResult> Index(string token)
And when i use the following line:
string url = Url.Action("Index", "Confirm", "mViH%2BZBz4l2%2Bx97rackKlFTWLVeD4xl9c%2B6ggbjbXzpAT%2BLP%2BKWvLqGymZSgV7GEPoXPSRHx6vO1ytaKPbfYrON%2BqP21EGMop3hW1%2BwoHL0Xf7bDSS5EHiqyuwNmiiJiMAYZPgr%2FCe%2FXyZFLCy%2FbfuGCOK3iawGOhdD0DyignbUC3xNybkfZkJNaXNHJlHnIv5eu8Z4wjzFkMmb1SOi5YmIzfT%2FjFovhy6fVFbDQXsc0GBzKqNsZjCudTKSPbMoRV6%2FAjw%3D%3D");
url ends up being:
"/Confirm?Length=292"
Instead of:
"/Confirm?token=mViH%2BZBz4l2%2Bx97rackKlFTWLVeD4xl9c%2B6ggbjbXzpAT%2BLP%2BKWvLqGymZSgV7GEPoXPSRHx6vO1ytaKPbfYrON%2BqP21EGMop3hW1%2BwoHL0Xf7bDSS5EHiqyuwNmiiJiMAYZPgr%2FCe%2FXyZFLCy%2FbfuGCOK3iawGOhdD0DyignbUC3xNybkfZkJNaXNHJlHnIv5eu8Z4wjzFkMmb1SOi5YmIzfT%2FjFovhy6fVFbDQXsc0GBzKqNsZjCudTKSPbMoRV6%2FAjw%3D%3D"
Does anyone know why this is the case? Nothing i've tried has worked to go around this. And if i create the link manually and use it it will work.

You need to provide route values.
An object that contains the parameters for a route. The parameters
are retrieved through reflection by examining the properties of the
object. The object is typically created by using object initializer
syntax.
string url = Url.Action("Index", "Confirm", new { token = "...." });

Related

How can I make a return with parameters in a View c# asp .net mvc?

Sorry for the title, but don't know how to explain it. (.NET ASP MVC)
So what I'm trying is to create a payment request via TripleA API(redirect on their page), if the payment is successful, they will redirect on my success page with some parameters, how can I handle those parameters?
What I've tried:
public IActionResult ErrorPage(string payment_reference, string status)
{
return View(payment_reference,status);
}
https://developers.triple-a.io/docs/triplea-api-doc/dd286311a5afc-make-a-payment-request
(scroll down to success_url for more info)
To expand on Steve's comment, create a record (less code than a class) as follows...
public record ErrorViewModel(string PaymentReference, string Status);
...then use this when you send data to the view...
public IActionResult ErrorPage(string payment_reference, string status)
{
return View(new ErrorViewModel(payment_reference,status));
}
You'll need to update your view to have the following line at the top...
#model ErrorViewModel
That should be all you need.
Based on the documentation, you expect a request like this,
https://www.myshop.com/payment-success?status=paid&payment_reference=ASDDF...&order_currency=USD&order_amount=10
And you translate that into a controller method,
[HttpGet("payment-success")]
public IActionResult ResultPage(string payment_reference, string status, string order_currency, decimal order_amount)
{
var result = new ResultViewModel(payment_reference,status, order_currency, order_amount);
return View(result);
}
I also noticed that the doc says,
Note: This field is required if integrating using External URL Payment Form. For other integrations, either insert the field with a url, or remove the field completely.
So if you use External URL Payment Form integration, then I don't think you will be able to get the status and reference.
The same applies for cancel_url.

Postman Testing send string to Web Api accepting string is null

I have been testing all the Get,Create,Update methods with Postman in which the Get passes in nothing. The Create and Update passes in raw json with Activity object with several properties that do match up with the C# class
So this signature for Create and Update works fine
[HttpPost]
public IHttpActionResult UpdateActivity(Activity activity)
Above works with Postman passing in JSON content type with all the properties. I have done this on OTHER projects.
HOWEVER
I'm trying to simply pass in a string and it is null no matter what
public IHttpActionResult DeleteActivity([FromBody]string Id)
{
// delete
var del = ActivityService.DeleteActivity(Id);
return Ok(del);
}
Postman I tried MANY ways
http://localhost:49810/api/activityapi/deleteactivity
I have tried MANY many ways based on blogs and google search one such example
{ "Id" = "5808786fa3e9ec79546b3c71" }
I know this is an older question but I wanted to help those who might have a similar problem as I was able to get this working.
In WebAPI Controller my method is setup as
[HttpPost]
public IHttpActionResult Create([FromBody] int eventId)
{
....
}
In order to get this to test properly in Postman you have to: In body, set to raw, make sure JSON (application/json) is set and then just add value like 2 that's it.. not like { "eventId":2 } which is proper JSON just the value and then it will work.
So in original poster's case, in Postman, if you set Body to raw, JSON (application/json) then "5808786fa3e9ec79546b3c71" as value it will work.
In Postman ensure the body is set to raw and select json and in the body just write "your string" in quotes. Do not use {} to surround it because that is to make a complex object
Try the following in the body, with the content-type as application/json
{ "5808786fa3e9ec79546b3c71" }
As when you specify it like so, it will attempt to de-serialize into a complex type with a property of Id
{ "Id" : "5808786fa3e9ec79546b3c71" }
Old question, but for those still wondering, I would recommend sending your string as a query parameter. Take a method like this for example:
[AllowAnonymous]
[HttpGet("resendEmailConfirmtionLink")]
public async Task<IActionResult> ResendEmailConfirmationLink(string email)
{
var user = await _userManager.FindByEmailAsync(email);
if (user == null) return Unauthorized();
var origin = Request.Headers["origin"];
var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
token = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(token));
var verifyUrl = $"{origin}/verifyEmail?token={token}&email={user.Email}";
var message = $"<p>Please click the below link to verify your email address:</p><p><a href='{verifyUrl}'>Click to verify email</a></p>";
await _emailSender.SendEmailAsync(user.Email, "Please verify email", message);
return Ok("Email verification link resent");
}
This method expects a key value pair of a string called email. You can send your request like "http://localhost:5000/api/account/verifyEmail?email=myemail#test.com" or, in Postman, add it as a parameter like this:
postman query params
Your payload is not valid.
Change-->
{ "Id" = "5808786fa3e9ec79546b3c71" }
To-->
{ "Id" : "5808786fa3e9ec79546b3c71" }
[HttpPost]
public IHttpActionResult Create(int eventId)
{
....
}
Use form-data instead of raw-json
Key - eventId
Value - "5808786fa3e9ec79546b3c71"
This worked for me.

Specify returnURL In QueryString

This is probably a simple question but I am struggling with returnurl in a querystring. I know how to call the returnurl in a querystring into a Response.Redirect but I am not sure how to set the returnurl to a certain url. Can someone give me a example of how to do this?
I have a suggestion for you, I'm sure how much it is apt for your situation.
Let me define a Static Dictionary<string,string> to save some key and corresponding URLs. Since it is statically defined you can access it from all other pages, this variable will get application scope. ie.,
public static Dictionary<string, string> URLDictonary = new Dictionary<string, string>()
{
{"google","http://google.com/"},
{"dotnet","http://www.dotnetperls.com/"},
{"querystring","http://www.dotnetperls.com/querystring"}
};
So that you can attach the key name with the URL as query string. It may look like the following:
Response.Redirect("~/Somepage.aspx?returnURL=google");
// Which means you are passing the key as query string
Now you can get this key in sample page and redirect to the specific page based on the key as follows:
string returnURL = Request.QueryString["returnURL"];
if (returnURL != null)
{
Response.Redirect(URLDictonary[returnURL]);
}
Since we are passing google it will redirect to the corresponding value ie. "http://google.com/".
Note : You can create similar Dictionary with your own keys and Urls. If it is defined in a different class then use class_name.DictonaryName[querystring_value]
You could do it in the following:
var url = Request.Url.ToString();
var uri = String.Format("http://example.com?page={0}", url);
Response.Redirect(uri);
The code is pretty straight forward.

How to use parameters as filters in MVC?

I think this is a simple question, but I somehow cannot sort it out. I have a List < SomeClass > that will be returned by an MVC controller. But, I want to filter the results server side. So suppose class is like:
public SomeClass()
{
string option1;
string option2;
int indexing;
}
Now I want to do a GET request, but the results need to be filtered on option1. So I can query the database properly. So I tried to jsonconvert.serialize an instance of the class with option1 set to 'something', but how can I deliver this to my MVC GET method? With httpclient there is no content, with httpWebRequest and writing it into a stream I have the error 'no content can be send with this verb', where verb is set to GET.
I think I am missing a basic thing here. Can anyone point me in the right direction?
if you want to keep your action as a GET, you need to call the action with the right querystring paramters i.e. /ActionName?option1=somevalue&option2=othervalue
and your action:
[HttpGet]
public ActionResult ActionName(SomeClass someclass)
or post the json option and chance your HttpGetverb to HttpPost
That's simple, you can use Json Result:
https://msdn.microsoft.com/en-us/library/system.web.mvc.jsonresult(v=vs.118).aspx
[HttpGet]
public ActionResult GetListObjects(string filter)
{
//getdata items
var objects =
from item in items
where (string)item.option1 == filter
select item;
return Json(objects, JsonRequestBehavior.AllowGet);
}

How To Send Value in HttpContext.Current.Response.Redirect?

I want to send an error message in HttpContext.Current.Response.Redirect
How should I do it?
HttpContext.Current.Response.Redirect("/Home/ErrorPage("the error is from here")");
public ActionResult ErrorPage(string error=")
{
return View(error);
}
How should I show the error inside the view?
Your URL is incorrect. You would need a result which has a valid Url encoded query string:
"/Home/ErrorPage?error=the+error+is+from+here";
However, instead of direct construction, you should use Html helper methods to build the url, e.g.:
Url.Action("ErrorPage", "Home", new {error = "the error is from here"});
You can also use TempData to pass once-off information:
Note that as per #Vsevolod's comment, that you shouldn't use Response.Redirect directly. Use an MVC RedirectResult or RedirectToAction from your controller, e.g.:
public ActionResult MethodReportingError()
{
TempData["Error"] = "Bad things happened";
return new RedirectResult(Url.Action("ErrorPage", "Home"));
}
public ActionResult ErrorPage()
{
return View(TempData["Error"]);
}
Where you want to pass Error. You are calling the information in url that is totally incorrect.
You can better pass information to error instead of url so it will make small and better url instead of blah blah in url.
Try to use Httpcontext.Controllers.ViewData to pass error to view and render the error there.

Categories

Resources