Click here to Skip to main content
15,895,192 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
See more:
hi
im just starting to use AMAZON API in my ASP.NET website. problem is i search lot about amazon api that how to use it in asp.net c# but i could not found anything best for my understanding. im just new for api so want just a simple code to show products on my website with buy link.

I have found a sample code but there are some errors like "The remote server returned an error: (400) Bad Request"
So please guys help me to fix errors or provide me some best code

THANKS

What I have tried:

C#
public partial class _Default : System.Web.UI.Page
     {
        //Set your Access Key and Secret Key in following variables.
        private const string MY_AWS_ACCESS_KEY_ID = "my access key";
        private const string MY_AWS_SECRET_KEY = "my secret key";
    private const string DESTINATION = "ecs.amazonaws.com";
    

    protected void Page_Load(object sender, EventArgs e)
    {
       
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        //Use SignedRequesthelper class to generate signed request. 
        SignedRequestHelper helper = new SignedRequestHelper(MY_AWS_ACCESS_KEY_ID, MY_AWS_SECRET_KEY, DESTINATION);

        IDictionary<string, string> requestParams = new Dictionary<string, String>();
        requestParams["Service"] = "AWSECommerceService";
        //Leave following line commented if you want to use latest version of Amazon API. You can uncomment this line to use a specific version.
        requestParams["Version"] = "2009-03-31";
        //requestParams["Operation"] = "ItemLookup";
        requestParams["Operation"] = "ItemSearch";
        requestParams["SearchIndex"] = selectCategories.Value;
        requestParams["Keywords"] = txtSearch.Text;

        //Get signed URL in a variable
        string requestUrl = helper.Sign(requestParams);
  
        //Get response from signed request
        DataSet DS = GetData(requestUrl);

        if (DS != null)
        {
            //Bind ItemAttributes table returned in dataset. This will give you product details.
            gridViewAttributes.DataSource = DS.Tables["ItemAttributes"];
            gridViewAttributes.DataBind();

            //Bind Item table returned in dataset. This will give you product link page.
            gridViewItem.DataSource = DS.Tables["Item"];
            gridViewItem.DataBind();
            lblError.Text = "";

            //You can set debug point here and inspect content of Datased(DS).
            //it has few more tables that you might be interested in.
        }
    }
        DataSet GetData(string signedurl)
    {
        try
        {
            //Create a request object using signed URL.
            WebRequest request = HttpWebRequest.Create(signedurl);
            //Get response in a stream          
            //WebRequest request = HttpWebRequest.Create(url);
            //WebResponse response = request.GetResponse();
            Stream responseStream = request.GetResponse().GetResponseStream();
            
          //  Stream responses = request.GetResponse().GetResponseStream();
            DataSet DS = new DataSet();
            //Read returned resonpse stream into a dataset.
            //Note: You can also use XMLDocument element here to read response.
            DS.ReadXml(responseStream);
            responseStream.Close();

            return DS;
        }
        catch (Exception e)
        {
            //If there is an error capture it.
            //If you get an error, it could be either because of invalid keyword or you provided wrong access key.
            lblError.Text = e.Message;
            Response.Write("Caught Exception: " + e.Message);
            Response.Write("Stack Trace: " + e.StackTrace);
        }

        return null;
    }
Posted
Updated 22-May-17 21:24pm
v3
Comments
manibsharma 23-May-17 1:06am    
Look like you are missing some parameter to be passed. Just make sure you have URL and parameters rightly in place. Please provide the stack trace of error to further see through details.
navi G 23-May-17 1:52am    
Caught Exception: The remote server returned an error: (400) Bad Request.Stack Trace: at System.Net.HttpWebRequest.GetResponse() at _Default.GetData(String signedurl)

1 solution

you are missing the Signature & timestamp parameters. Also check your service URL, it should be [Link of service]

I was able to access the service with below parameters.

[Link to service with parameters]
 
Share this answer
 
Comments
OriginalGriff 23-May-17 3:44am    
Please do not repost if your submission is not immediately visible: you were sent to moderation where a human has to decide if it is suitable for publication.
I have deleted the two spare answers.
manibsharma 23-May-17 4:34am    
Thanks a lot for information. Next time I will take care
OriginalGriff 23-May-17 4:44am    
You're welcome!
navi G 26-May-17 11:43am    
hi manibsharma

Thanks dear i appreciate your help.
but i want to ask some other questions . 1 here i have share some more info about my sample code it is from SignRequestHelper.cs plse tell me what is wrong with its. i have checked code with your suggestions like Signature & timestamp . it is already provided in sample code . and id you think there is problem in code then plse tell me what should i do. plse it is more understandable for me if you help me with edit my code and post thanks
navi G 26-May-17 11:45am    
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Security.Cryptography;

namespace AmazonProductAdvtApi
{
public class SignedRequestHelper
{
private string endPoint;
private string akid;
//private string associateTag;
private byte[] secret;
private HMAC signer;

private const string REQUEST_URI = "/onca/xml";
private const string REQUEST_METHOD = "GET";

//
// * Use this constructor to create the object. The AWS credentials are available on
// * http://aws.amazon.com
// *
// * The destination is the service end-point for your application:
// * US: ecs.amazonaws.com
// * JP: ecs.amazonaws.jp
// * UK: ecs.amazonaws.co.uk
// * DE: ecs.amazonaws.de
// * FR: ecs.amazonaws.fr
// * CA: ecs.amazonaws.ca
//

public SignedRequestHelper(string awsAccessKeyId, string awsSecretKey, string destination)
{
this.endPoint = destination.ToLower();
this.akid = awsAccessKeyId;
this.secret = Encoding.UTF8.GetBytes(awsSecretKey);
//this.associateTag = associateTag;
this.signer = new HMACSHA256(this.secret);
}

//
// * Sign a request in the form of a Dictionary of name-value pairs.
// *
// * This method returns a complete URL to use. Modifying the returned URL
// * in any way invalidates the signature and Amazon will reject the requests.
//

public string Sign(IDictionary<string, string> request)
{
// Use a SortedDictionary to get the parameters in naturual byte order, as
// required by AWS.
ParamComparer pc = new ParamComparer();
SortedDictionary<string, string> sortedMap = new SortedDictionary<string, string>(request, pc);

// Add the AWSAccessKeyId and Timestamp to the requests.
sortedMap["AWSAccessKeyId"] = this.akid;
sortedMap["Timestamp"] = this.GetTimestamp();
//sortedMap["AssociateTag"] = this.associateTag;
// Get the canonical query string
string canonicalQS = this.ConstructCanonicalQueryString(sortedMap);

// Derive the bytes needs to be signed.
StringBuilder builder = new StringBuilder();
builder.Append(REQUEST_METHOD).Append("\n").Append(this.endPoint).Append("\n").Append(REQUEST_URI).Append("\n").Append(canonicalQS);

string stringToSign = builder.ToString();
byte[] toSign = Encoding.UTF8.GetBytes(stringToSign);

// Compute the signature and convert to Base64.
byte[] sigBytes = signer.ComputeHash(toSign);
string signature = Convert.ToBase64String(sigBytes);

// now construct the complete URL and return to caller.
StringBuilder qsBuilder = new StringBuilder();
qsBuilder.Append(" http://").Append(this.endPoint).Append(REQUEST_URI).Append("?").Append(canonicalQS).Append("&Signature=").Append(this.PercentEncodeRfc3986(signature));

return qsBuilder.ToString();
}

//
// * Sign a request in the form of a query string.
// *
// * This method returns a complete URL to use. Modifying the returned URL
// * in any way invalidates the signature and Amazon will reject the requests.
//

public string Sign(string queryString)
{
IDictionary<string, string> request = this.CreateDictionary(queryString);
return this.Sign(request);
}

//
//

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900