簡體   English   中英

在傳遞單個字符串參數時從 MVC 5 controller 調用 Web API Post 方法

[英]Calling Web API Post method from MVC 5 controller while passing single string parameter

所以我正在調試我的應用程序,並且在我的 MVC 應用程序旁邊運行了一個 web API。 我只是想在傳遞字符串參數時調用 web API post 方法。

一般信息:

  1. 使用 .NET 框架 4.5.2

  2. 想要將字符串參數發送為 JSON 並接收 HttpResponseMessage 作為 JSON

WEB API 項目控制器:

這是我試圖調用的 web api 方法。

[HttpPost]
    public HttpResponseMessage CreateStandardSchematic(string modelToCreate)
    {
        string check = _eplanConnectionService.CreateProject(modelToCreate, "");
        var NewProjectLog = new NewProjectLogDTO
        {
            ErrorMessage = check == "Success" ? "Success" : check,
            PassFail = check == "Success" ? "Pass" : "Fail",
            MaterialNumber = modelToCreate,
        };
        return Request.CreateResponse(System.Net.HttpStatusCode.OK, NewProjectLog);
    }

MVC Controller:

這是我的 MVC 5 項目,我只是想調用上面的 web api 方法。

public JsonResult CreateStandardSchematics(List<MaterialViewModel> listOfMaterials, string clientId)
    {
        using (var client = new HttpClient())
        {
            //using JSON
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var stringContent = new StringContent(listOfMaterials[0].Material);//passing material number as string

            //This is the portion I am unsure about. I see a lot of online suggestions saying 
            //to use PostAsJsonAsync but I do not have access to the libraries. I would prefer 
            //to use PostAsync() but am unsure how to format the correct query string I believe?
            var responseTask = client.PostAsync("http://localhost:44344/api/Project?modelToCreate=", stringContent);
            responseTask.Wait();

            var result = responseTask.Result;
            if (result.IsSuccessStatusCode)
            {
                var readTask = result.Content.ReadAsStringAsync().Result;
                //Deserialize object
                var deserialized = JsonConvert.DeserializeObject<List<NewProjectLogViewModel>>(readTask);
            }
            else //web api sent error response 
            {
                //log response status here..
            }
        }
        //Other stuff
    }

這是我第一次嘗試同時調試我的 web api 和 mvc 項目。 如果您對如何從 MVC 5 Web 項目正確調用 Asp.Net Web API Post 方法(帶有簡單查詢字符串參數)有任何建議,請指向正確的方向。

編輯

因此,在環顧四周后,我意識到 java 腳本字符串也可能是錯誤的。 這就是我現在所擁有的。

public JsonResult CreateStandardSchematics(List<MaterialViewModel> listOfMaterials, string clientId)
    {
        try
        {
            using (var client = new HttpClient())
            {
                //using JSON
                string modelToCreate = "modelToCreate:" + listOfMaterials[0].Material;
                var stringContent = new StringContent(JsonConvert.SerializeObject(modelToCreate), //passing material number as string
                    UnicodeEncoding.UTF8, "application/json");
                var check = stringContent.ReadAsStringAsync().GetAwaiter().GetResult();

                //This is the portion I am unsure about. I see a lot of online suggestions saying 
                //to use PostAsJsonAsync but I do not have access to the libraries. I would prefer 
                //to use PostAsync() but am unsure how to format the correct query string I believe?
                var responseTask = client.PostAsync("http://localhost:44344/api/Project", stringContent);
                responseTask.Wait();

                var result = responseTask.Result;
                if (result.IsSuccessStatusCode)
                {
                    var readTask = result.Content.ReadAsStringAsync().Result;
                    //Deserialize object
                    var deserialized = JsonConvert.DeserializeObject<List<NewProjectLogViewModel>>(readTask);
                }
                else //web api sent error response 
                {
                    //log response status here..
                }
            }
        }
        catch (Exception ex)
        {

            //
        }
    }

檢查返回以下似乎仍然錯誤的內容:

在此處輸入圖像描述

編輯2:

我的 API function 現在看起來如下所示:我正在嘗試將數據作為正文內容而不是查詢字符串發布。 (我在第一篇文章中感到困惑)。 但現在我對發生的事情有了更好的了解。 似乎即使使用此當前設置,我在 web api 中的調試斷點仍未達到,並且發布請求超時。

[HttpPost]
    public HttpResponseMessage CreateSchematic([FromBody] MaterialViewModel modelToCreate)
    {
        string check = _eplanConnectionService.CreateProject(modelToCreate.Material, "");
        var NewProjectLog = new NewProjectLogDTO
        {
            ErrorMessage = check == "Success" ? "Success" : check,
            PassFail = check == "Success" ? "Pass" : "Fail",
            MaterialNumber = modelToCreate.Material,
        };
        return Request.CreateResponse(System.Net.HttpStatusCode.OK, NewProjectLog);
    }

現在這是我的 MVC controller:

我簡化了這一點,所以沒有那么多垃圾給每個人看。 我開始使用 object 而不是一個名為MaterialViewModel的簡單字符串(參見下面的 class):

public JsonResult CreateStandardSchematics(List<MaterialViewModel> listOfMaterials, string clientId)
    {
        using (var client = new HttpClient())
        {
            //using JSON
            var stringContent = new StringContent(JsonConvert.SerializeObject(listOfMaterials[0]), //passing material number as string
                UnicodeEncoding.UTF8, "application/json");
            var check = stringContent.ReadAsStringAsync().GetAwaiter().GetResult();
            //This is the portion I am unsure about. I see a lot of online suggestions saying 
            //to use PostAsJsonAsync but I do not have access to the libraries. I would prefer 
            //to use PostAsync() but am unsure how to format the correct query string I believe?
            var responseTask = client.PostAsync("http://localhost:44344/api/Project", stringContent);
            responseTask.Wait();
            var result = responseTask.Result;
            if (result.IsSuccessStatusCode)
            {
                var readTask = result.Content.ReadAsStringAsync().Result;
                //Deserialize object
                var deserialized = JsonConvert.DeserializeObject<List<NewProjectLogViewModel>>(readTask);
            }
        }
    }

材質視圖模型:

public class MaterialViewModel
{
    public string Material { get; set; }
}

我的檢查現在顯示在發布之前正在構建以下字符串:

在此處輸入圖像描述

謝謝!

通常,HTTP POST 請求假定請求的主體包含參數。 在您的情況下,如果您想通過查詢字符串傳遞參數,您必須使用 web API 中的[FromUri]屬性,如下所示,

public HttpResponseMessage CreateStandardSchematic([FromUri]string modelToCreate)

要將有效字符串傳遞給參數,您只需將值作為查詢字符串傳遞,如下所示,

 var responseTask = client.PostAsync(String.Format("http://localhost:44344/api/Project?modelToCreate={0}",listOfMaterials[0].Material);

由於發布的信息很少,很難確定發生了什么,但我有一些話要說,你可以試試。

  1. 看起來您的 POST 方法沒有使用任何正文,因此您可以將其轉換為 GET 如果這對您來說沒問題。

  2. 刪除帶有隨機端口的硬編碼 URI。 當您運行/調試 Web API 項目時,它會不時改變。 如果要硬編碼,請在屬性 window 中設置 static 端口。

  3. 您實際上並不需要此代碼

    var check = stringContent.ReadAsStringAsync().GetAwaiter().GetResult();
  4. 如果這不是查詢字符串參數,則調用 POST URI 的方式很好。 如果您希望它成為查詢字符串,則您的 URI 需要反映這一點。

看看 ThangaDurai 在他的第二行中發布的內容。 傳遞 body 是您現在正在做的事情,而不是查詢參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM