Hello friends i have created Asp.net core web service and calling this web service form web application. in this web api user upload pdf and document type and File number.
this is my asp.net core controller
[HttpPost ]
[Route("v1/ReceiveNoteData")]
public string ReceiveNoteData([FromBody] ReceiveNoteDataReq request)
{
return _IReceiveNoteData.ReceiveNoteDataResponse(request);
}
ReceiveNoteDataReq class
public class ReceiveNoteDataReq
{
public byte[] DocumentBody { get; set; }
public string DocType { get; set; }
public string FileNumber { get; set; }
}
when i am trying to call this web service using webrequest on service side frombody always getting NULL
if i am sending only file number and doc type i am getting data in from body but when i am trying to send pdf data from body getting NULL.
this is how i am calling the web service in my web application.
ReceiveNoteDataReq req = new ReceiveNoteDataReq()
req.DocumentBody = bytes;// pdf byte data
req.FileNumber = txtid.Text;
req.DocType = doctype;
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
string url = "http://localhost:905/v1/ReceiveNoteData";
CookieContainer cookieJar = new CookieContainer();
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.MediaType = "application/json";
webRequest.Accept = "application/json";
webRequest.CookieContainer = cookieJar;
webRequest.KeepAlive = true;
webRequest.UserAgent = #"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36";
webRequest.Credentials = CredentialCache.DefaultCredentials;
StreamWriter writer = new StreamWriter(webRequest.GetRequestStream());
JavaScriptSerializer jss = new JavaScriptSerializer();
string yourdata = jss.Serialize(req); // here i am converting class to json string.
writer.Write(yourdata);
writer.Close();
var myWebResponse = webRequest.GetResponse();
var responseStream = myWebResponse.GetResponseStream();
if (responseStream != null)
{
var myStreamReader = new StreamReader(responseStream, Encoding.Default);
result = myStreamReader.ReadToEnd();
}
Thanks in advance.
when i am trying to call this web service using webrequest on service side frombody always getting NULL if i am sending only file number and doc type i am getting data in from body but when i am trying to send pdf data from body getting NULL.
If you'd like to post pdf data with other information from request body to you backend service, you can refer to the following example.
//...
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
string yourdata = System.Text.Json.JsonSerializer.Serialize(
new
{
DocType = doctype,
FileNumber = txtid.Text,
DocumentBody = base64String
});
writer.Write(yourdata);
writer.Close();
//...
The ByteArrayModelBinder can help bind data to byte[] DocumentBody property well.
public class ReceiveNoteDataReq
{
[ModelBinder(BinderType = typeof(ByteArrayModelBinder))]
public byte[] DocumentBody { get; set; }
public string DocType { get; set; }
public string FileNumber { get; set; }
}
Test Result
Besides, as #SabirHossain mentioned, you can try to modify your code to upload file through FormData, and this SO thread discussed similar requirement, you can refer to it.
Related
i'm new on creating Rest API using PHP. I have create one, my codes works but i'm not sure about it, here is the code :
// connect to the mysql database
$link = mysql_connect('localhost', 'root', 'pass');
mysql_select_db('database',$link);
// retrieve the table and key from the path
$nama_tujuan = preg_replace('/[^a-z0-9_]+/i','',array_shift($request));
$nama_tabel = preg_replace('/[^a-z0-9_]+/i','',array_shift($request));
//Menu Login
if($nama_tujuan=="login")
{
$username = preg_replace('/[^a-z0-9_]+/i','',array_shift($request));
$password = preg_replace('/[^a-z0-9_]+/i','',array_shift($request));
if($method=='GET')
{
$sql = "select * from $nama_tabel where username_reg='$username' and pass_reg='$password'";
$result = mysql_query($sql,$link);
if (!$result) {
http_response_code(404);
die(mysql_error());
}
$cek_user=mysql_num_rows($result);
//cek user
if($cek_user==1)
{
//Kirim data yang dperlukan
for ($i=0;$i<mysql_num_rows($result);$i++)
{
echo ($i>0?',':'').json_encode(mysql_fetch_object($result));
}
}
}
}
for example i try it with:
http://localhost/api.php/login/member/neo/qw
and it show all of the fields like this :
{"nik":"46464646457349187","username_reg":"neo","nm_dpn_reg":"neo","nm_blg_reg":"alit","email_reg":"neo#neo.com","pass_reg":"qw","jns_kel":"P","pin_reg":"111111","tmp_lahir_reg":"lumajang","tgl_lahir_reg":"1-1-1945","alamat_reg":"jolotundo","kota_reg":"surabaya","kd_pos":"60131","propinsi":"Aceh","alamat_kirim":"","kota_kirim":"","kdpos_kirim":"","propinsi_kirim":"","wilayah":"jawa","tlp_hp_reg":"08964507555","tgl_daf":"2016-04-27 16:32:00","ikut_resel":"","bonus":"0"}
Is this called Rest API? And my second question, i want to get JSON data on my Android app, i'm using Visual Studio 2015 and Xamarin. I already create some code, but i don't know the rest, because i'm new on developing android app. Here is my activity code :
button.Click += async (sender, e) => {
string url = "http://localhost/api.php/login/login_mbr/" +
txtUsername.Text +
"/" +
txtPassword.Text;
string m = JsonConvert.DeserializeObject<string>(await FetchWeatherAsync(url));
// ParseAndDisplay (json);
};
}
private async Task<string> FetchWeatherAsync(string url)
{
// Create an HTTP web request using the URL:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
request.ContentType = "application/json";
request.Method = "GET";
}
Thanks in advance :)
You can get the json string by this:
private async Task<string> FetchWeatherAsync (string url)
{
// Create an HTTP web request using the URL:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create (new Uri (url));
request.ContentType = "application/json";
request.Method = "GET";
// Send the request to the server and wait for the response:
using (WebResponse response = await request.GetResponseAsync ())
{
// Get a stream representation of the HTTP web response:
using (Stream stream = response.GetResponseStream ())
{
string strContent = sr.ReadToEnd();
return strContent;
}
}
}
now this already returns you the JSON.
If you want to deserialize the JSON into the object you should create the object with the specified properties like:
public class WeatherResult ()
{
public string nik {get; set;}
public string username_reg {get; set;}
...
...
...
}
and then you can get it by
WeatherObject result = JsonConvert.DeserializeObject<WeatherResult>(await FetchWeatherAsync(url));
If you don't want to create new object you can use dynamic object
dynamic result = JObject.Parse(await FetchWeatherAsync(url));
Note: you need Newtonsoft library for JSON.
I have been trying to integrate BeanStream payment gateway with my product from last three days. But unfortunately I am getting 401 authentication error every time. I have performed following steps.
1) Created a test account.
2) Generated API Pass Code from Configuration -> Payment Profile Configuration -> Security Settings.
3) Got merchant Id from top section.
4) Created an HttpWeb request using the sample code provided on BeanStream developer portal. Below is the code for that.
string url = "https://www.beanstream.com/api/v1/payments";
BeanStreamRequest req = new BeanStreamRequest
{
order_number = "10000123",
amount = 100.00m,
payment_method = "",
card = new Card {
name = "abc",
number = "5100000010001004",
expiry_month = "02",
expiry_year = "18",
cvd = "642"
}
};
JavaScriptSerializer js = new JavaScriptSerializer();
string jsonString = js.Serialize(req);
string merchantId = "MERCHANT_ID";
string apiPassCode = "API_PASS_CODE";
string base64_encode = String.Format("{0}{1}{2}",merchantId,":",apiPassCode);
string authorization = String.Format("{0}{1}", "Passcode ", Convert.ToBase64String(Encoding.ASCII.GetBytes(base64_encode)));
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.Accept = "*/*";
webRequest.Headers[HttpRequestHeader.Authorization] = authorization;
//webRequest.Headers.Add("Authorization ", authorization);
webRequest.ContentType = "application/json";
webRequest.ContentLength = jsonString.Length;
StreamWriter writer = null;
writer = new StreamWriter(webRequest.GetRequestStream());
writer.Write(jsonString);
writer.Close();
string responseString;
try
{
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{
using (StreamReader responseStream = new StreamReader(webResponse.GetResponseStream()))
{
responseString = responseStream.ReadToEnd();
}
}
}
catch (WebException ex)
{
if (ex.Response != null)
{
using (HttpWebResponse errorResponse = (HttpWebResponse)ex.Response)
{
using (StreamReader reader = new StreamReader(errorResponse.GetResponseStream()))
{
string remoteEx = reader.ReadToEnd();
}
}
}
}
Any help?
The issue you are having is that you are creating an API Key (Passcode) for a Payment Profile API (http://developer.beanstream.com/documentation/tokenize-payments/) and then using it in a Payments API (http://developer.beanstream.com/documentation/take-payments/). These two resources use different API Keys (Passcodes). See "Where is my API Passcode?" on http://developer.beanstream.com/documentation/your-first-integration/. Create an API Key for Payments API and everything should work as expected.
I'm working on project in which I'm Posting data from asp.net webform to WCF service. I'm posting data through params and the service respond me back a JSON string. Now I have an issue in deserialize. I read many threads but didn't find any solution. Hope someone can sort out my problem. Thanks in Advance
Response from WCF
{"LoginResult":false}
I just want "false" value.
How I tried:
string URL = "http://localhost:32319/ServiceEmployeeLogin.svc";
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(URL+"/"+emp_username+"/"+emp_password+"/"+emp_type);
wrGETURL.Method = "POST";
wrGETURL.ContentType = #"application/json; charset=utf-8";
HttpWebResponse webresponse = wrGETURL.GetResponse() as HttpWebResponse;
Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
// read response stream from response object
StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(), enc);
// read string from stream data
strResult = loResponseStream.ReadToEnd();
var jObj = JObject.Parse(strResult);
var dict = jObj["LoginResult"].Children().Cast<JProperty>();
You could use json.net to do it like this:
public class AuthResponse {
public bool LoginResult { get; set; }
}
var deserializedResponse = JsonConvert.DeserializeObject<AuthResponse>(strResult);
http://james.newtonking.com/json
.Net 4.5 has a JavaScriptSerializer, which should work as well:
public class AuthResponse {
public bool LoginResult { get; set; }
}
System.Web.Script.Serialization.JavaScriptSerializer sr = new System.Web.Script.Serialization.JavaScriptSerializer();
AuthResponse response = sr.Deserialize<AuthResponse>(responseText);
http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer%28v=vs.110%29.aspx
I've only worked with APIs in a very minimal sense so I've been wanting to try out how to do this for some time. Ok so this is what I have so far and it works but it returns everything of the definition. So I have a few questions:
Is there a way to request just the definitions without anything else?
Do I just parse the data? I saw in the Wordnik API and I can include XML tags...so can I use an XMLReader to grab the definitions?
Now how about requesting both the definitions and if it is noun/verb/etc at once?
The ultimate goal would be to create a list of definitions that I could do stuff with. Any help would be greatly appreciated. Here's my code so far:
class Program
{
static void Main(string[] args)
{
string apiKey = "***************";
string wordToSearch = "";
do
{
Console.Write("Please type a word to get the definition: ");
wordToSearch = Console.ReadLine();
if (!wordToSearch.Equals("q"))
{
string url = "http://api.wordnik.com/v4/word.json/" + wordToSearch + "/definitions?api_key=" + apiKey;
WebRequest request = WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/json";
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
string responseFromWordnik = reader.ReadToEnd();
Console.WriteLine(responseFromWordnik);
}
}
}
} while (!wordToSearch.Equals("q"));
}
}
thanks,
Justin
Here's an example to get definitions for a word. You need to replace the api key with your own api key.
public class Word
{
public string word { get; set; }
public string sourceDictionary { get; set; }
public string partOfSpeech { get; set; }
public string text { get; set; }
}
public class WordList
{
public List<Word> wordList { get; set; }
}
string url = "http://api.wordnik.com:80/v4/word.json/" + word + "/definitions?limit=200&includeRelated=false&sourceDictionaries=all&useCanonical=false&includeTags=false&api_key=a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5";
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = WebRequestMethods.Http.Get;
webRequest.Accept = "application/json";
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36";
webRequest.Referer = "http://developer.wordnik.com/docs.html";
webRequest.Headers.Add("Accept-Encoding", "gzip, deflate, sdch");
webRequest.Headers.Add("Accept-Language", "en-US,en;q=0.8");
webRequest.Host = "api.wordnik.com";
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
string enc = webResponse.ContentEncoding;
using (Stream stream = webResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
String responseString = "{\"wordList\":" + reader.ReadToEnd() + "}";
if (responseString != null)
{
JavaScriptSerializer ser = new JavaScriptSerializer();
WordList words = ser.Deserialize<WordList>(responseString);
}
}
The API documentation will probably tell you that.
Yes, parse the data. If the data is coming down as XML, then you can parse it with an XMLReader, or you can load it into an XMLDocument. It looks like you're asking for JSON, though. If so, you'll want a JSON parser. Check out Json.Net.
Again, check out the API documentation.
Their documentation page is suspiciously sparse. You'll probably get better response on their Google group or one of the other sources listed on their support page.
I created a Rest Webservice with ASP.NET MVC 4 Web Application. If I want to consume the service and send a request including a requestbody the input parameter CoreMessage item is always null. I watched some sample tutorials and some sample code but I couldn't fix the bug.
Some code of my Rest Client
CoreMessage message = new CoreMessage() { Source = "Dummy", Date = DateTime.Now, Data = "abcd" };
var url = "http://localhost:12294/api/message";
var method = "POST";
string reponseAsString = "";
try
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
using (Stream requestStream = request.GetRequestStream())
using (StreamWriter writer = new StreamWriter(requestStream))
{
writer.Write(message);
}
}
catch (Exception ex)
{
reponseAsString += "ERROR: " + ex.Message;
}
My Controller with the Post function look like this
public MessageRepository repository = new MessageRepository();
public HttpResponseMessage PostMessage(CoreMessage item)
{
bool status = repository.TransmitMessage(item);
var response = Request.CreateResponse<bool>(HttpStatusCode.Created, status);
return response;
}
My Model
public class CoreMessage
{
public string Source { get; set; }
public DateTime Date { get; set; }
public string Data { get; set; }
}
There are few things to try
First, put [FromBody] attribute:
public HttpResponseMessage PostMessage([FromBody] CoreMessage item)
Then try to add Content-Type header to your request
request.ContentType = "application/json; chatset=utf-8"
And you have to make it JSON before writing to stream, you cannot write the object out like that. The method depends on what framework you use for JSON serialisation. One of the most popular one is JSON.NET, which is dead easy to install through NuGet package manager. Once you got it installed you can serialise your CoreMessage to string like:
string messageString = JSONConvert.SerializeObject(message);
Then writing it in UTF-8 encoding:
using (StreamWriter writer = new StreamWriter(requestStream, Encoding.UTF8))
{
writer.Write(messageString);
}
After all, if it's still not working, you can try Dev HTTP Client in Chrome. The tool will allow you to craft raw HTTP request. Your request should have Content-Type as application/json; charset=utf-8 and POST data as JSON string.