Unable to post to aspnet webapi using angular http - asp.net-mvc

I have created a simple webapi controller.
// POST request api to get a string base64 image, store it and returns its name.
public string Post([FromBody]string image)
{
if (image == null)
return "No image sent";
// Generating random file name using the current date and time and random text
string fileName = "image-" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + Path.ChangeExtension(
Path.GetRandomFileName(),
".jpg"
);
// If the directory does not exist create a new one
if (!Directory.Exists(#".\uploads\"))
{
DirectoryInfo DI = Directory.CreateDirectory(#".\uploads\");
}
File.WriteAllBytes(#".\uploads\" + fileName, Convert.FromBase64String(image));
return "Submitted as File: " + fileName;
}
When I send a post request through postman, it works as fine and returns the string "Submitted as File ..."
But when I try it in Angular I get the following error.
OPTIONS http://example.com/Api/Image/Index 405 (Method Not Allowed)
My angular service:
getResult(base64image) {
//Where base64image is a string.
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post('http://example.com/Api/Image/Index', base64image, options)
.map(res => res);
}
I know that it has something to with cors. But it is just a simple api.

Related

Trying to upload media to the Meta Whatsapp API but running into errors

Context: I need to send media templates in which I need to send local files. Thus I need to upload the files to the WhatsApp API to get the Media Id, which I can then use to send the message templates.
The issue: I am running into errors while sending the post request to the server through DART. However the same call is working when sent through postman. I have tried sending the data both as a JSON and as form-data, but both are returning errors. I am attaching the code below, as well as the errors I am facing. Any help is really appreciated.
Getting the file path
upload() async{
if(await Permission.storage.isGranted){
FilePickerResult? choice = await FilePicker.platform.pickFiles(allowMultiple: false);
String? path = choice?.files.single.path;
if(path != null){
uploadJson(path);
// uploadFormData(path);
}
}else{
Permission.storage.request();
}
}
Uploading JSON
uploadJson(String path) async{
File imgfile = File(path);
Uint8List imgbytes = await imgfile.readAsBytes();
String bs4str = base64.encode(imgbytes);
print(bs4str);
var headers = {
'Authorization': variables.authorizationToken,
"Content-Type": 'application/json',
};
var body = jsonEncode({
'file': '$bs4str;type=image/jpeg',
'messaging_product':'whatsapp'
});
Response response = await post(Uri.parse('${variables.baseURL}${variables.phoneNumberId}/media'), headers: headers, body: body);
print(response.body);
}
Uploading as Form-data
uploadFormData(String path) async {
var headers = {
'Authorization': 'Bearer EAAGtvNhUHUIBANf5KvyxnZCUKcRn3jTJgPZBR2AbbVhZBZBO7GjoDCnS26FQT6Nr6qdRV993ZCJEbGwiqZCdQ7TZBJX8S6KXQdOTgmSf9ue7GCEN1IL3yqfAUEIN1bw0nyvptHeZBFCsdfwpxZAcS1ZCbCdmqArZC81orVbYRkzJy1h7ChOAygmrchfFtJAapykZAadruFqOWwcVvtudMezse94zENBNVZA0k7pAZD',
};
var request = MultipartRequest('POST', Uri.parse('https://graph.facebook.com/v14.0/106822672107550/media'));
request.fields.addAll({
'messaging_product': 'whatsapp'
});
request.files.add(await MultipartFile.fromPath('file', path));
request.headers.addAll(headers);
Response response = await Response.fromStream(await request.send());
print(response.body);
}
Error for JSON:
flutter: {"error":{"message":"An unknown error has occurred.","type":"OAuthException","code":1,"fbtrace_id":"AE72st2KT8wJFQ_wYvrcJY6"}}
Error for Form-Data:
flutter: {"error":{"message":"(#100) Param file must be a file with one of the following types: audio\/aac, audio\/mp4, audio\/mpeg, audio\/amr, audio\/ogg, audio\/opus, application\/vnd.ms-powerpoint, application\/msword, application\/vnd.openxmlformats-officedocument.wordprocessingml.document, application\/vnd.openxmlformats-officedocument.presentationml.presentation, application\/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application\/pdf, text\/plain, application\/vnd.ms-excel, image\/jpeg, image\/png, image\/webp, video\/mp4, video\/3gpp. Received file of type 'application\/octet-stream'.","type":"OAuthException","code":100,"fbtrace_id":"AfsxKl38CW7hUF_ixMzNha9"}}
The problem was with the Mime-type of the file. The Multi-Part file class needed the mime-type of the file to be declared while uploading the file, or the file was automatically being uploaded as an octlet-stream. The code to the working request is posted below.
var request = http.MultipartRequest('POST', Uri.parse('https://graph.facebook.com/v14.0/${variables.phoneNumberId}/media'));
request.headers.addAll({
'Authorization': variables.authorizationToken,
'Content-Type': 'multipart/form-data'
});
request.fields.addAll({
'messaging_product': 'whatsapp',
'type': 'application/pdf'
});
// The MIME type of the image or file
const mimeType = 'application/pdf';
// Open the image file
var file = File(path);
// Create a MultipartFile from the File object
final multipartFile = await http.MultipartFile.fromPath(
'file',
file.path,
contentType: MediaType.parse(mimeType),
);
// Create a request body containing the multipart file
request.files.add(multipartFile);
// Send the request
final response = await request.send();
// Check the response status code
if (response.statusCode == 200) {
String body = await response.stream.bytesToString();
var json = jsonDecode(body);
print(json['id']);
} else {
print(response.reasonPhrase);
}

Login authentication using token error Access-Control-Allow-Origin'

userAuthentication(userName, password) {
let headers = new Headers();
var data = "username=" + userName + "&password=" + password + "&grant_type=password";
// var reqHeader = new HttpHeaders({ 'Content-Type': 'application/x-www-urlencoded','No-Auth':'True' });
headers.append('Content-Type', 'application/x-www-urlencoded');
headers.append('Access-Control-Allow-Origin', '*');
headers.append('No-Auth','True');
headers.append('Access-Control-Allow-Methods', 'GET, POST, PUT');
return this.http.post(environment.apiUrl + 'token', data, { headers: headers })
.pipe(map(data => data.json()),
catchError((error: any) => {
throw error;
}));
}
}
I am using angular on client side and asp.net mvc on server side.I an facing an error Access-Control-Allow-Origin
The Error you got is because you don't have required permissions to access API
add this line inside your API code
you have to install cors first
Install-Package Microsoft.AspNet.WebApi.Cors
after add this line inside your API
config.EnableCors();
"config" refers to httpconfiguration class
you will now able to access your API

How to pass JSON string to another api using RESTSharp?

Problem Specification:
Resource URI : address/index.php?r=api/employee
Request Header : Content- Type: application/json
HTTP Method: POST
Request Body: { "employeeName" : "ABC","age":"20","ContactNumber": "12341234"}
The above parameters should be passed to the system as a row HTTP POST in a JSON string.
I am trying to solve this problem using RESTSharp. But I am having some problem Like after executing the request my code return a Null response and I am not sure my JSON string is passing properly or not.
Here is my Code:
public ActionResult EmployeeInfo(Employee employee)
{
//string empName = unSubscription.employeeName.ToString();
var client = new RestClient("http://localhost:21779/");
var request = new RestRequest("api/employee ", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(new Employee
{
employeeName = "ABC",
age = "20",
ContactNumber = "12341234"
});
request.AddHeader("Content-Type", #"application/json");
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
return View();
}
Is there anything wrong with my code??
And I am little bit confused about
request.AddUrlSegment("username", "Admin") and request.AddParameter("name", "value").
Basically I want to know how to utilize AdduUrlSegment() and AddParameter().
Thanks in advance.
For using request.AddUrlSegment("username", "Admin") you should define your url template properly: var request = new RestRequest("api/employee/{username} ", Method.POST);
Also you should set Content-Type
request.AddHeader("Content-Type", #"application/json");
befor adding a Body

How can I upload a PDF using Dart's HttpClient?

I need to post a PDF file to a remote REST API, and I can't for the life of me figure it out. No matter what I do, the server responds that I have not yet associated an object with the file parameter. Let's say that I have a PDF called test.pdf. This is what I've been doing so far:
// Using an HttpClientRequest named req
req.headers.contentType = new ContentType('application', 'x-www-form-urlencoded');
StringBuffer sb = new StringBuffer();
String fileData = new File('Test.pdf').readAsStringSync();
sb.write('file=$fileData');
req.write(sb.toString());
return req.close();
Thus far, I've tried virtually every combination and encoding of the data that I write() to the request, but to no avail. I've tried sending it as codeUnits, I've tried encoding it using a UTF8.encode, I've tried encoding it using a Latin1Codec, everything. I'm stumped.
Any help would be greatly appreciated.
You can use MultipartRequest from the http package :
var uri = Uri.parse("http://pub.dartlang.org/packages/create");
var request = new http.MultipartRequest("POST", url);
request.fields['user'] = 'john#doe.com';
request.files.add(new http.MultipartFile.fromFile(
'package',
new File('build/package.tar.gz'),
contentType: new ContentType('application', 'x-tar'));
request.send().then((response) {
if (response.statusCode == 200) print("Uploaded!");
});
Try using the multipart/form-data header rather than x-www-form-urlencoded. This should be used for binary data, also can you show your full req request?
void uploadFile(File file) async {
// string to uri
var uri = Uri.parse("enter here upload URL");
// create multipart request
var request = new http.MultipartRequest("POST", uri);
// if you need more parameters to parse, add those like this. i added "user_id". here this "user_id" is a key of the API request
request.fields["user_id"] = "text";
// multipart that takes file.. here this "idDocumentOne_1" is a key of the API request
MultipartFile multipartFile = await http.MultipartFile.fromPath(
'idDocumentOne_1',
file.path
);
// add file to multipart
request.files.add(multipartFile);
// send request to upload file
await request.send().then((response) async {
// listen for response
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}).catchError((e) {
print(e);
});
}
I used file picker to pick file.
Here is the codes for pick file.
Future getPdfAndUpload(int position) async {
File file = await FilePicker.getFile(
type: FileType.custom,
allowedExtensions: ['pdf','docx'],
);
if(file != null) {
setState(() {
file1 = file; //file1 is a global variable which i created
});
}
}
here file_picker flutter library.

SharePoint: How to create a folder in a document library please using web services

I need to create a simple folder in a document library in SharePoint, but I can't seem to find a scrap of documentation on the subject.
The dws webservice seems to be used to create physical folders in a workspace, I need a way to create a folder in a document library.
Not sure what to do , please help
I found this method to work :
HttpWebRequest request = (System.Net.HttpWebRequest)HttpWebRequest.Create("http://mySite/MyList/MyfolderIwantedtocreate");
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = "MKCOL";
HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
response.Close();
This is the code for similar request in JAVA using apache HttpClient
import org.apache.http.*;
private static HttpResponse makeFolder(
String url,
DefaultHttpClient httpClient) throws Exception {
BasicHttpRequest httpPost = new BasicHttpRequest("MKCOL", url);
HttpUriRequest httpUriRequest = new RequestWrapper(httpPost);
HttpResponse status = httpClient.execute(httpUriRequest);
EntityUtils.consume(status.getEntity());
return status;
}
Code to create the httpClient and call the makeFolder Function
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getCredentialsProvider().setCredentials(
AuthScope.ANY,
new NTCredentials(config.getUserName(), config.getPasswords(),
"", config.getDomain()));
I know this is a pretty old question, but in case someone else finds it, this is how I've done it:
String CAML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body>" +
"<CreateFolder " + "xmlns=\"http://schemas.microsoft.com/sharepoint/soap/dws/\">"+
"<url>" + ParentFolder+'/'+NewFolderName+ "</url>"+
"</CreateFolder>"+
"</soap:Body>" +
"</soap:Envelope>";
String uri = "http://[your site]/_vti_bin/dws.asmx";
WebClient client = new WebClient();
client.Headers["SOAPAction"] = "http://schemas.microsoft.com/sharepoint/soap/dws/CreateFolder";
client.Headers["content-type"] = "text/xml; charset=utf-8";
client.Encoding = Encoding.UTF8;
client.UploadStringCompleted += UploadStringCompleted;
try
{
client.UploadStringAsync(new Uri(uri, UriKind.Absolute), "POST", CAML);
}
catch (Exception ex)
{
MessageBox.Show("Error in upload string async: " + ex.Message);
}
I was using silverlight, which is why I used upload string async, but this can be done other ways with the same http post method
I've done some work with the Web services but I can't find any code that creates a folder. However, I have code that copies files from a network share to an existing folder in a SharePoint document library using UNC paths. It uses System.IO.File - perhaps you could use that technique to create a folder?
Created folders in sharepoint by using Document Workspace Web Service (Dws). Works great.
public static bool CreateSPFolder(string FolderDir, string FolderName, yourCredentialsClass credentials)
{
FolderName = ReplaceInvalidChars(FolderName);
// create an instance of the sharepoint service reference
Dws.Dws dwsWebService = new Dws.Dws();
dwsWebService.Url = credentials.SharePointUrl + "/_vti_bin/Dws.asmx";
dwsWebService.Credentials = new NetworkCredential(credentials.UserId, credentials.Password);
string result = dwsWebService.CreateFolder(string.Format("{0}/{1}",FolderDir,FolderName));
dwsWebService.Dispose();
if (result == null)
{
throw new Exception("No response creating SharePoint folder");
}
if (result.Equals("<Result/>"))
{
return true;
}
return false;
}
public static string ReplaceInvalidChars(string strIn)
{
return Regex.Replace(strIn.Replace('"', '-'), #"[.~#%&*{}:<>?|/]", "-");
}

Resources