我写了一个Postman可以调用的API,没问题。但是,当我尝试从另一个C#项目中调用我的API时,该API会接收NULL数据。这是我的API控制器(邮递员称之为,没问题):
public class BuildVirtualMachineController : ApiController
{
public HttpResponseMessage Post(VirtualMachine virtualMachine)
{
System.ComponentModel.DataAnnotations.ValidationContext vc = new ValidationContext(virtualMachine);
ICollection<ValidationResult> results = new List<ValidationResult>();
bool isValid = Validator.TryValidateObject(virtualMachine, vc, results, true);
if(!isValid)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
string theReturn = JenkinsREST.BuildVirtualMachine(virtualMachine);
return Request.CreateResponse(HttpStatusCode.OK, theReturn);
}
您可以看到它需要JSON,可以将其转换为VirtualMachine对象。这是邮递员发送给它的:
{
"Hostname": "pocdua133",
"IPAddress": "172.30.32.133",
"ResourceGroup": "hud-edw-poc-rg",
"StorageAccount": "sapocimages",
"BaseImage": "Windows 2016"
}
这没有问题。现在,这是我的应用程序中用于调用API的代码,这是即使数据相同也得到空值的时间:
protected void BuildBtn_BuildVirtualMachine(Object sender, EventArgs e)
{
using (var wb = new WebClient())
{
string url = "http://localhost:54587/api/v1/BuildVirtualMachine";
string queryString = @"{ ""Hostname:""" + Hostname.Text + @""",IPAddress:""" + IPAddress.Text + @""",ResourceGroup:""" + ResourceGroups.SelectedItem.Text + @""",StorageAccount:""" + StorageAccount.Text + @""",BaseImage:""" + BaseImage.Text + @"""}";
string password = "73c986bcaae14a6a93d345c270f3e1ba";
string username = "admin";
string basicAuthToken = Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password));
wb.Headers["Authorization"] = "Basic " + basicAuthToken;
wb.Headers[HttpRequestHeader.ContentType] = "application/json";
wb.Headers.Add("user", "admin:73c986bcaae14a6a93d345c270f3e1ba");
string response = wb.UploadString(url, queryString);
WebHeaderCollection results = wb.ResponseHeaders;
//return results.ToString();
}
}
这是我的API中定义的虚拟机模型,如果有帮助的话:
public class VirtualMachine
{
[Required(ErrorMessage = "Hostname is required.")]
public string Hostname { get; set; }
[Required(ErrorMessage = "IP address is either not given or in improper format")]
[RegularExpression(@"^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$")]
public string IPAddress { get; set; }
[Required(ErrorMessage = "Resource group is required.")]
public string ResourceGroup { get; set; }
[Required(ErrorMessage = "Storage account is required.")]
public string StorageAccount { get; set; }
[Required]
public string BaseImage { get; set; }
[System.ComponentModel.DefaultValue("Standard_DS2_v2")]
public string VMSize { get; set; }
[System.ComponentModel.DefaultValue("apps")]
string VHDContainer { get; set; }
}
我使用了类似的代码来调用其他API,而JSON看起来与Postman中的相同,那么为什么POST总是给我的API提供一个null值,而Postman却没有呢?
谢谢!
杜安(Duane)