如何使用Web API Post传递JSON值

时间:2019-07-02 09:55:16

标签: c# asp.net-mvc asp.net-web-api web-api-testing

我只想使用带有基本身份验证,用户名测试和密码test123的webapi将Json参数传递给(http://localhost:8700/api/signals/Web_Collection?commit=true

当我单击按钮时,它会转到FusionApi.cs,并且在将json值传递到api url时遇到问题。

我需要添加基本身份验证(用户名测试和密码 test123)。

对于Params,它具有commit=true 对于标题,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代码:

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()});               

            }
        }

1 个答案:

答案 0 :(得分:0)

如果您确实必须使用json字符串执行此操作,则可以按照以下步骤操作:

1。 将您的字符串转换为有效的json或仅使用正确的json字符串:

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

2。 然后使用WebUtility将json字符串编码为url编码的字符串 并将其写入您的网址。您必须考虑如何调用queryParameter, 在此示例中,我将其称为“ json”:

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

否则,我会这样做:

  1. 对于基本身份验证,我先转换用户名和密码 到Base64String:
string userNamePassword = Settings.Default.UserName + ":" + Settings.Default.Password;
string authenticationToken = Convert.ToBase64String(Encoding.ASCII.GetBytes(userNamePassword));

2。 之后,我将“ authenticationToken”添加到HttpClient中:

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authenticationToken);