0

I just want to pass the Json params to (http://localhost:8700/api/signals/Web_Collection?commit=true) using webapi with Basic Authentication, with username test and password test123

When I click the button its going to FusionApi.cs and I having issue to pass the json value to api url.

I need to add the Basic Authentication (Username : test & Password : test123).

For Params it has commit=true For Headers, content-Type: "application/json”

[
 {"params": {
      "query": "Service",
      "filterQueries": ["!haslayout_b:false","searchable_s:false"],
      "docId": "http://web_intranet/{8f31bf38-069e-4ce7-a108-b3e7903fd26c}?lang=en&ver=2&ndx=sitecore_web_index" },
 "type":"test",
 "timestamp": "2015-05-10T19:05:00.000Z"
 }
]

HTML :

<body>

    <div class="container">
        <div class="row" style="margin-top:25px;">
            <div class="col-md-4">
                <label>Query:</label>
            </div>
            <div class="col-md-6">
                <input type="text" class="form-control" id="Query">
            </div>
        </div>
        <div class="row" style="margin-top:10px;">
            <div class="col-md-4">
                <label>FilterQueries-haslayout_b:</label>
            </div>
            <div class="col-md-6">
                <label class="radio-inline"><input type="radio" name="haslayout_b" value="true">True</label>
                <label class="radio-inline"><input type="radio" name="haslayout_b" value="false" checked>False</label>
            </div>
        </div>
        <div class="row" style="margin-top:10px;">
            <div class="col-md-4">
                <label>FilterQueries-searchable_s:</label>
            </div>
            <div class="col-md-6">
                <label class="radio-inline"><input type="radio" name="searchable_s" value="true">True</label>
                <label class="radio-inline"><input type="radio" name="searchable_s" value="false" checked>False</label>
            </div>
        </div>
        <div class="row" style="margin-top:10px;">
            <div class="col-md-4">
                <label>DocId:</label>
            </div>
            <div class="col-md-6">
                <textarea class="form-control" rows="5" id="DocId"></textarea>
            </div>
        </div>
        <div class="row" style="margin-top:25px;">
            <div class="col-md-4">
                <label>Type:</label>
            </div>
            <div class="col-md-6">
                <input type="text" class="form-control" id="Type" value="click" disabled>
            </div>
        </div>
        <div class="row" style="margin-top:25px;">
            <div class="col-md-4">
                <label>Timestamp:</label>
            </div>
            <div class="col-md-6">
                <input type="date" value="@System.DateTime.Today.ToShortDateString()" id="Timestamp" disabled>
            </div>
        </div>
        <button type="button" onclick="FusionPost()" class="btn btn-success" style="float:right;">Submit</button>
    </div>
</body>
</html>

<script>
    function FusionPost() {
        debugger;
        var FusionValue = {
            query: $("#Query").val(),
            haslayout_b: $("input[name='haslayout_b']:checked").val(),
            searchable_s: $("input[name='searchable_s']:checked").val(),
            docId: $("#DocId").val(),
            type: $("#Type").val(),
            timestamp: $("#Timestamp").val()
        };

            $.ajax({
                type: "POST",
                url: "@Url.Action("FusionApi", "Fusion")",
                datatype: "JSON",
                data: { FusionValue},
                success: function (Result) {                       
                    console.log(Result.type);

                }
            })    };
</script>

Cs Code :

public JsonResult FusionApi(Fusions FusionValue)
        {
            try
            {

                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.TryAddWithoutValidation(name: "Username", value: "test");
                    client.DefaultRequestHeaders.TryAddWithoutValidation(name: "Password", value: "test123");
                    client.DefaultRequestHeaders.Add(name: "Accept", value: "application/json");

                    client.BaseAddress = new Uri("http://localhost:8700/api/signals/Web_Collection?commit=true");
                    string url = "http://localhost:8700/api/signals/Web_Collection?commit=true";                   

                    HttpResponseMessage response = client.PostAsJsonAsync(url, new Fusions { docId = FusionValue.docId}).Result;                    
                     int responsestate = (int)response.StatusCode;
                    return Json(new { type = responsestate });
                }               
            }
            catch (Exception ex)
            {            
                return Json(new { type = ex.ToString()});               

            }
        }
Ram Anugandula
  • 582
  • 4
  • 15
DloveJ
  • 13
  • 1
  • 1
  • 8
  • 2
    Possible duplicate of [Setting Authorization Header of HttpClient](https://stackoverflow.com/questions/14627399/setting-authorization-header-of-httpclient) – Orel Eraki Jul 02 '19 at 10:44
  • how can i add this .cs [ {"params": { "query": "Service", "filterQueries": ["!haslayout_b:false","searchable_s:false"], "docId": "http://web_intranet/{8f31bf38-069e-4ce7-a108-b3e7903fd26c}?lang=en&ver=2&ndx=sitecore_web_index" }, "type":"test", "timestamp": "2015-05-10T19:05:00.000Z" } ] – DloveJ Jul 02 '19 at 11:24
  • please check this img - https://ibb.co/TP22SBm – DloveJ Jul 02 '19 at 11:31

1 Answers1

0

If you really HAVE TO do it using a json string, I would do it like following:

1. Convert your string to a valid json or just use your correct json string:

TestClass testClass = new TestClass();
testClass.Username = "test";
testClass.Password = "test123";
string json = JsonConvert.SerializeObject(testClass);

2. Then use WebUtility to encode your json string into a url-encoded string and write it into your url. You have to consider how your queryParameter is called, for this example I have called it "json":

var jsonToken = WebUtility.UrlEncode(json);
client.BaseAddress = new Uri("http://localhost:8700/api/signals/Web_Collection?commit=true?json=" + jsonToken);

OTHERWISE I would do it that way:

  1. For the Basic Authentication I would first convert the username and the password to a Base64String:
string userNamePassword = Settings.Default.UserName + ":" + Settings.Default.Password;
string authenticationToken = Convert.ToBase64String(Encoding.ASCII.GetBytes(userNamePassword));

2. After that I would add the "authenticationToken" to the HttpClient:

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authenticationToken);
U_M4D_BR0
  • 36
  • 4