首先,我不确定我的问题是否反映了我的需求,如果需要更改,请告诉我。
我在这里所做的是在 DLL 应用程序中创建函数,以便从 C# 之外的 DotNET 调用。我的函数现在的问题是模型类。在我要使用此 DLL 的地方,我无法从外部查看/使用我的模型类,因此如何更改我的代码以使用字符串而不是产品模型?不过,我仍然需要以 JSON 形式发送我的请求。
第 1 类 (
SetupWebAPIAsync
):放置产品(模型)的功能
public static async Task<ApiResponse> PutProductAsync(string endpoint, Product p)
{
StringContent httpContent = new StringContent(JsonConvert.SerializeObject(p), Encoding.UTF8, "application/json");
string result = "";
HttpResponseMessage response = await client.PutAsync(endpoint, httpContent);
response.EnsureSuccessStatusCode();
result = await response.Content.ReadAsStringAsync();
return new ApiResponse(response.StatusCode, result);
}
二年级:
public static ApiResponse PutIn(string user, string password, string endpoint , Product Httpcontent)
{
User = user;
Password = password;
Endpoint = endpoint;
Content = Httpcontent;
ExecutePUTRequest().Wait();
return apiResponse;
}
private static async Task ExecutePUTRequest()
{
SetupWebAPIAsync.SetAPIAuthentication(User, Password);
apiResponse = await SetupWebAPIAsync.PutProductAsync(Endpoint,Content);
}
我的模特班:
public class Product
{
public string id { get; set; }
public string name { get; set; }
public bool inactive { get; set; }
}
ex:
{
"id" : "12",
"name" : "test",
"inactive": false,
}
现在这就是我调用函数的方式,它以这种方式工作,但我需要用从 Dll 外部测试传入的字符串替换产品。
Product product = new Product { name = "API_Testing" };
PutIn("user", "pass", "https://localhost/api/product", product);
好吧,你不能让你的
PutIn()
方法需要 Product Httpcontent
作为方法参数。相反,将字符串化的产品作为 JSON 并将其转换为 product
并调用 main 方法,如
public static ApiResponse PutIn(string user, string password,
string endpoint , string Httpcontent)
{
User = user;
Password = password;
Endpoint = endpoint;
Content = NewtonSoft.Json.JsonConvert.DeserializeObject<Product>(Httpcontent);
ExecutePUTRequest().Wait();
return apiResponse;
}
然后你可以这样称呼它
string product = "{id : 12,name : API_Testing,inactive: false,}"
PutIn("user", "pass", "https://localhost/api/product", product);