POSTing to an ASP MVC 4 site from a C# Windows application - c#

I'm writing a Windows application that will communicate with an ASP MVC site.
The site has a controller method for POST requests that passes to it an object from my Model.
I have access to those same classes in my desktop application and was hoping that I would be able to create an object of the same type, then create an HTTP POST request, attach the object and send it to the site.
I found that the POST data is just key-value pairs that match the properties of the class so Property1=value1&Property2=value2 worked, however I'm stumped as to how to represent a list.
Is there some easy way to serialise the object into an HTTP request or would I have to make multiple requests for each item in the list?

You can use WebClient to implement such behavior
string url = "your POST action url here";
NameValueCollection formData = new NameValueCollection();
formData["name"] = "John";
// add more form field / values here
WebClient webClient = new WebClient();
byte[] responseBytes = webClient.UploadValues(url, "POST", formData);
string response = Encoding.UTF8.GetString(responseBytes);
However, this is not good practice. This kind of communication should be implemented with web services - if your application is designes well (for example you have service layer/repository), there is nothing easier than expose simple webservice side by side with MVC frontend.

Related

C# - How to POST form data to a PHP file and permanently redirect the user to the url?

I have an ASP.NET CORE checkout page, razor page, which contains an HTML Form. The payment process will be completed by a php file pay.php. I want to POST the Form Data, from backend (in C#) to a url that reaches a php file pay.php for processing.
So far I have code that POST form data but I want to redirect the user to the url. The processing will be handled by the pay.php and the result of the process success or process fail willbe rendered from the pay.php.
How do I achieve that? or what would you recommend is the best approach to POST from C# to PHP and then redirect the user to the url, if possible, permanet redirect?
The pay.php file will be on the same server with the ASP.NET CORE APP.
Here is the code I use to POST from C# to PHP:
[HttpPost]
public async Task<IActionResult> Checkout(FormDataModel model)
{
string URL = "https://websitename.com/checkout/pay.php";
using (WebClient webClient = new WebClient())
{
NameValueCollection formData = new NameValueCollection();
formData["firstName"] = "John";
formData["lastName"] = "Doe";
formData["email"] = "johndoe#email.com";
webClient.UploadValuesAsync(new Uri(URL), "POST", formData);
}
}
Now I am not sure how to redirect the user to the url (https://websitename.com/checkout/pay.php) so that they see the posted values. I hope to resolve this by your help.

How to read data from WebClient.UploadData

First time posting! I've been breaking my head on this particular case. I've got a Web application that needs to upload a file towards a web-api and receive an SVG file (in a string) back.
The web-app uploads the file as follows:
using (var client = new WebClient())
{
var response = client.UploadFile(apiUrl, FileIGotEarlierInMyCode);
ViewBag.MessageTest = response.ToString();
}
Above works, but then we get to the API Part:
How do I access the uploaded file? Pseudocode:
public string Post([FromBody]File f)
{
File uploadedFile = f;
String svgString = ConvertDataToSVG(uploadedFile);
return s;
}
In other words: How do I upload/send an XML-file to my Web-api, use/manipulate it there and send other data back?
Thanks in advance!
Nick
PS: I tried this answer:
Accessing the exact data sent using WebClient.UploadData on the server
But my code did not compile on Request.InputStream.
The reason Request.InputStream didn't work for you is that the Request property can refer to different types of Request objects, depending on what kind of ASP.NET solution you are developing. There is:
HttpRequest, as available in Web Forms,
HttpRequestBase, as available in MVC Controllers
HttpRequestMessage, as available in Web API Controllers.
You are using Web API, so HttpRequestMessage it is. Here is how you read the raw request bytes using this class:
var data = Request.Content.ReadAsByteArrayAsync().Result;

Authenticating requests to external REST service

I'm really new to web development, and I don't really have a good grip on the main concepts of web. However, I've been tasked with writing an asp.net application where users can search documents by querying an external RESTful web service. Requests to this REST service must be authenticated by HTTP Basic Authentication.
So far so good, I've been able to query the service using HttpWebRequest and HttpWebResponse, adding the encoded user:pass to the request's authorization header, deserialize the Json response and produce a list of strings with url's to the pdf documents resulting from the search.
So now I'm programmatically adding HyperLink elements to the page with these urls:
foreach (string url in urls) {
HyperLink link = new HyperLink();
link.Text = url;
link.NavigateUrl = url;
Page.Controls.Add(link);
}
The problem is that requests to these documents has to be authorized with the same basic http authentication and the same user:pass as when querying the REST service, and since I'm just creating links for the user to click, and not creating any HttpWebRequest objects, I don't know how to authenticate such a request resulting from a user clicking a link.
Any pointers to how I can accomplish this is very much appreciated. Thanks in advance!
You probably want to do the request server-side, as I think you're already doing, and then show the results embedded in your own pages, or just stream the result directly back to the users.
It's a bit unclear what it is you need (what are the links, what do you show the users, etc.), so this is the best suggesting I can do based on the info you give.
Update:
I would create a HttpHandler (an .ashx file in an ASP.NET project), and link to that, with arguments so you can make the request to the REST service and get the correct file, then stream the data directly back to the visitor. Here's a simple example:
public class DocumentHandler : IHttpHandler {
public Boolean IsReusable {
get { return true; }
}
public void ProcessRequest(HttpContext context) {
// TODO: Get URL of the document somehow for the REST request
// context.Request
// TODO: Make request to REST service
// Some pseudo-code for you:
context.Response.ContentType = "application/pdf";
Byte[] buffer = new WebClient().DownloadData(url);
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
context.Response.End();
}
}
I hope you can fill in the blanks yourself.

HttpWebRequest not being received correctly in MVC ASP.NET

This is me publicly documenting my mistake so that if I or anyone does it again, they don't have to spend 3 hours tearing their hair out trying to fix such a simple thing.
Context
I was sending an HttpRequest from one C# MVC ASP.NET application to another.
The applications require an HTTPS connection, and we are using URLRewrite to redirect an HTTP request to an HTTPS url.
One application was sending a POST request with some JSON data in the body, pretty standard stuff. The other application was set up to receive this data with an MVC controller class (CollectionAction and Insert methods for GET and POST respectively).
Symptoms of the problem
The receiving application was running the GET method (CollectionAction) instead of the POST action (ItemAction). The reason for this was that the request coming in to the application was in fact a GET request, and to top it off the JSON data was missing too.
I sent the header "x-http-method" to override the request method from GET to POST (I was already setting the request httpmethod to POST but this was being ignored). This worked but still I had no data being sent.
So now I am stuck pulling my hair out, because I can see a POST request with content-length and data being sent out and I have a GET request with no data or content-length coming in (but the headers were preserved)
Turns out I was using UriBuilder to take a base URL and apply a resource path to it. For example I would have "google.com" in my web.config and then the UriBuilder would take a resource like Pages and construct the url "google.com/Pages". Unfortunately, I was not initializing the UriBuilder with the base URL, and instead was using a second UriBuilder to extract the host and add that to the path like so:
public Uri GetResourceUri(string resourceName)
{
var domain = new UriBuilder(GetBaseUrl());
var uribuilder = new UriBuilder()
{
Path = domain.Path.TrimEnd('/') + "/" + resourceName.TrimStart('/'),
Host = domain.Host
};
var resourceUri = uribuilder.Uri;
return resourceUri;
}
The problem with this code is that the scheme is ignored (HTTP:// vs HTTPS://) and it defaults to HTTP. So my client was sending out the request to an HTTP url instead of the required HTTPS url. This is the interesting part, URLRewrite was kicking in and saying that we needed to go to an HTTPS url instead so it redirected us there. But in doing so, it ignored the Http-Method and the POST data, which just got set to defaults GET and null. This is what the 2nd application could see at the receiving end.
So the function had to be rewritten to this which fixed the problem:
public Uri GetResourceUri(string resourceName)
{
var baseUrl = GetBaseUrl();
var domain = new UriBuilder(baseUrl);
var uribuilder = new UriBuilder(baseUrl)
{
Path = domain.Path.TrimEnd('/') + "/" + resourceName.TrimStart('/'),
};
var resourceUri = uribuilder.Uri;
return resourceUri;
}

Generate http post request from controller

Forgive me if this is a stupid question. I am not very experienced with Web programming.
I am implementing the payment component of my .net mvc application. The component interacts with an external payment service. The payment service accepts http post request in the following form
http://somepaymentservice.com/pay.do?MerchantID=xxx&Price=xxx&otherparameters
I know this is dead easy to do by adding a form in View. However, I do not want my views to deal with third party parameters. I would like my view to submit information to my controller, then controller generates the required url and then send out the request. Following is the pseudo code.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult PayForOrder(OrderForm order)
{
var url = _paymentService.GetUrlFromOrder(order);
SendPostRequest(url);
return View("FinishedPayment");
}
Is it possible to do so? Does c# have built-in library to generate http request?
Thanks in advance.
You'll want to use the HttpWebRequest class. Be sure to set the Method property to post - here's an example.
There certainly is a built in library to generate http requests. Below are two helpful functions that I quickly converted from VB.NET to C#. The first method performs a post the second performs a get. I hope you find them useful.
You'll want to make sure to import the System.Net namespace.
public static HttpWebResponse SendPostRequest(string data, string url)
{
//Data parameter Example
//string data = "name=" + value
HttpWebRequest httpRequest = HttpWebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.ContentLength = data.Length;
var streamWriter = new StreamWriter(httpRequest.GetRequestStream());
streamWriter.Write(data);
streamWriter.Close();
return httpRequest.GetResponse();
}
public static HttpWebResponse SendGetRequest(string url)
{
HttpWebRequest httpRequest = HttpWebRequest.Create(url);
httpRequest.Method = "GET";
return httpRequest.GetResponse();
}
It realy makes a difference if ASP.NET makes a request or the the client makes a request.
If the documentation of the the provider says that you should use a form with the given action that has to be submited by the client browser then this might be necessary.
In lots of cases the user (the client) posts some values to the provider, enters some data at the providers site and then gets redirected to your site again. You can not do this applicationflow on the serverside.

Categories

Resources