WebResponse to HttpResponseBase. Is it possible? - asp.net-mvc

In a controller action, I am manually sending a form to a remote URL using WebRequest. I successfully receive a WebResponse containing an html page to display. I would like to "paste" this response as the Response (of type HttpResponseBase) of the action. An action normally returns an ActionResult, so how do I conclude my controller action so that the WebResponse will be the result?
Note: the Url in the browser must also become the url of the response.
Update: Here is the goal. This is on a paypal checkout page. Instead of having a form with all cart hidden fields and a checkout submit button in my view, I would like a simple checkout button linked to one of my actions. In this action, I will prepare the WebRequest with the form and send it to paypal. Doing this in an action also allows me to store the inactivated order in a DB table so that when the order confirmation comes I can compare it with the stored order and activate it.
Solution: thanks to those who answered for pointing out that this would not be possible to redirect with a POST. It appears that I am not obliged to redirect to paypal with a POST. Instead I can construct a URL with all the cart data in the query string and redirect to it. Doing it from a controller action method still allows me to store the pending order in a database.
Thanks

If you just want the content of the WebRequest response to be sent back in the response from your controller action, you could do something like this in your action method:
WebRequest req = WebRequest.Create("http://www.google.com");
WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
ContentResult cr = new ContentResult();
cr.Content = sr.ReadToEnd();
return cr;
this is even more concise:
WebRequest req = WebRequest.Create("http://www.google.com");
WebResponse res = req.GetResponse();
FileStreamResult fsr = new FileStreamResult(res.GetResponseStream(),res.ContentType);
return fsr;

THere is no direct way to do this. I dont know much about ASp.NET. ARe you saying that your ASP.net page is doing a HTTP request to a remote site, and getting back a response, and you want that response to become a HTTPResponseBase? What do you want to do with it after that?
See the following SO thread on a similar topic...
How do I mock HttpResponseBase.End()?

Related

How to handle query string in Asp.net MVC 5

I have an ASP.NET MVC 5 website. I have used action link while designing table to display a list of data. while navigating from that action link I have passed a class object as a parameter. After visiting that link, it parses that object parameter as long query string which exposes data in the URL.
What is the way to handle a query string in MVC?
Is it possible to hide query string or way to pass an object as a parameter without exposing it in the URL?
You can not hide the query string, it is part of the URL. You could encrypt it tho.
One solution would be to use a POST request instead of a GET. Then you can send the data in the body of the request, it will not show up in the URL. But it will still be accessible if you inspect the network traffic (e.g. if you run Fiddler on the client computer).
Another solution would be to still use a GET request, but instead of passing all the data, just pass an ID, then load the data again from the database using this ID. Note that this ID can be spoofed too, so make sure the User has actually the permissions to request this ID.
#Html.ActionLink("Show details", "Details", "Data", new { dataId = Model.Id })
[HttpGet]
public ActionResult Details(long dataId) {
var data = _dbContext.Data.Find(dataId);
var vm = new DataDetailsViewModel(data);
return View("Details", vm);
}

MVC Redirect to a different view in another controller

After a user has completed a form in MVC and the post action is underway, I am trying to redirect them back to another view within another model.
Eg. This form is a sub form of a main form and once the user has complete this sub form I want them to go back to the main form.
I thought the following might have done it, but it doesn't recognize the model...
//send back to edit page of the referral
return RedirectToAction("Edit", clientViewRecord.client);
Any suggestions are more that welcome...
You can't do it the way you are doing it. You are trying to pass a complex object in the url, and that just doesn't work. The best way to do this is using route values, but that requires you to build the route values specifically. Because of all this work, and the fact that the route values will be shown on the URL, you probably want this to be as simple a concise as possible. I suggest only passing the ID to the object, which you would then use to look up the object in the target action method.
For instance:
return RedirectToAction("Edit", new {id = clientViewRecord.client.ClientId});
The above assumes you at using standard MVC routing that takes an id parameter. and that client is a complex object and not just the id, in which case you'd just use id = clientViewRecord.client
A redirect is actually just a simple response. It has a status code (302 or 307 typically) and a Location response header that includes the URL you want to redirect to. Once the client receives this response, they will typically, then, request that URL via GET. Importantly, that's a brand new request, and the client will not include any data with it other than things that typically go along for the ride by default, like cookies.
Long and short, you cannot redirect with a "payload". That's just not how HTTP works. If you need the data after the redirect, you must persist it in some way, whether that be in a database or in the user's session.
If your intending to redirect to an action with the model. I could suggest using the tempdata to pass the model to the action method.
TempData["client"] = clientViewRecord.client;
return RedirectToAction("Edit");
public ActionResult Edit ()
{
if (TempData["client"] != null)
{
var client= TempData["client"] as Client ;
//to do...
}
}

How to get the raw binary content in Grails controller

after many days of search and many unsuccessful tries, I hope that the community knows a way to achieve my task:
I want to use grails as a kind of a proxy to my solr backend. By this, I want to ensure that only authorized requests are handled by solr. Grails checks the provided collection and the requested action and validated the request with predefined user based rules. Therefore, I extended my grails URL mapping to
"/documents/$collection/$query" {
controller = "documents"
action = action = [GET: "proxy_get", POST: "proxy_post"]
}
The proxy_get method works fine even when the client is using solrJ. All I have to to is to forward the URL request to solr and to reply with the solr response.
However, in the proxy_post method, I need to get the raw body data of the request to forward it to solr. SolrJ is using javabin for that and I was not able so far to get the raw binary request. The most promising approach was this:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(solrUrl);
InputStream requestStream = request.getInputStream();
ContentType contentType = ContentType.create(request.getContentType());
httpPost.setEntity(new ByteArrayEntity(IOUtils.toByteArray(requestStream), contentType));
httpPost.setHeader("Content-Type", request.getContentType())
HttpResponse solrResponse = httpClient.execute(httpPost);
However, the transferred content is empty in case of javabin (e.g. when I add a document using solrJ).
So my question is, whether there is any possibility to get to the raw binary post content so that I can forward the request to solr.
Mathias
try using Groovy HttpBuilder. It has a powerful low-level API, while providing groovyness

How to send Form Data from Controller

I am working on this project, where my Application need to connect to a third party application.
My steps
Create form to submit data.
Get Form data in MY controller Action. Save mine required variables to database.
Then send the data to Third Party Application.
Now the problem here is that, i need to send the data as Submit Form.
The Third party app takes the values as
Request.form("FormVal")
I can make no changes to the Third party Application.
So how do i send the Form data through my Controller action to the Third Party application?
Also
return view("action", model); // the model is needed to be sent.
it works for the view in my own Application. However I need to send it to an external view(third party) with the model so they can get value as
Request.form("FormVal")
I see the Redirect commands can go the external view but i cannot send the form Data with it.
You can use HttpClient to send data to the third party application.
like this:
var formValues = new Dictionary<string,string>();
formValues.Add("Key", "Value");
HttpResponseMessage response = await httpClient.PostAsync(thirdPartyUrl, new FormUrlEncodedContent(formValues));
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Edited:
If you are not using .NET Framework 4.5 you can use the WebClient.UploadValues instead.
byte[] responseArray = myWebClient.UploadValues(thirdPartyUrl,myNameValueCollection);
the HttpResponseMessage was not what i actually wanted. I also needed to redirect.
So I used javascript/jquery for this.
I created two views
1st is the user input view.
2nd is the Redirect View
From the 1st view I post to my controller then, call my redirect view from the controller action
return view("redirectView", model);
In the Redirect view I created a form with hidden inputs.
#HiddenFor(m=>m.SomeValue)
Then on page load i used javascript to Submit the form.
$("form#formID").submit();
This works for me right now.
Also thanks to Kambiz for making me understand this issue.

Show querystring after POST

I'm using MVC4/Razor. After a GET request the view shows the querystring, and after a POST request the view does not show the querystring - both as expected.
But, I have an action with [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)], and I need to POST a form to it, and to show the corresponding querystring.
How can I do this on the server side? I know this can be done on the client side by converting to a GET request, and I am curious to see how to do that, but only if that is the only way to make this work.
You can return RedirectToAction with posted parameters
return RedirectToAction("About", "Create",
new { id = PId, Name=PName }); // more params if needed
The parameters will be included in the querystring.

Resources