Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload file form powershell to asp.net

I have an asp.net mvc application, which allows to upload company structure using CSV file. I was asked about possibility to automate this function using powershell script.Creating CSV in powershell is easy, but I do not have an idea how upload to asp.net.

My first choice was to use WebClient, but I have problem with authentication - in mvc we are using forms authentication.I read here that it is possible, but if my login form changes I will have to send updated script to client. I would like to omit mange code on client side.

The second option is to crate separate controller and use in it authorization token, but I look like "inventing a wheel again", because I would need to write all code responsible for authentication.

Can I improve one of above options? Or maybe there is a better choice?

like image 896
Piotr Stapp Avatar asked Apr 14 '13 18:04

Piotr Stapp


1 Answers

You might be able to use the existing web service using the Invoke-RestMethod cmdlet, but it could take two separate invokes. For both invocations you'll probably need to say -Method Post. Its possible to do all this with WebClient, but the cmdlet may be easier to describe. I haven't actually tried this, but it could look something like this:

Invoke-RestMethod -Method Post $loginPage -SessionVariable webSession -Body "..."
Invoke-RestMethod -Method Post $uploadPage -WebSession $webSession -Body "..."

For the first invocation, you specify the URL of the login page, and would simulate a web forms login by providing a username and password in the -Body parmeter, and use -SessionVariable to capture and store context for making the next request(s) authenticated.

In the second request, you use your data upload URL, the -WebSession parameter to supply the context established by the first request, and -Body to upload your CSV. Note that you need the dollar sign on the webSession variable in the second one, but not the first.

Of course, you'll need to store the username/password for the automation to use somewhere, but that's always needed for unattended automation. A possible slick approach to mitigate this would be to use client certificate-based credentials rather than a web form authentication.

like image 103
Burt_Harris Avatar answered Nov 06 '22 21:11

Burt_Harris