在xamarin.forms
中使用 .net Web API 将数据发布到sql时出错StatusCode: 204, ReasonPhrase: 'No Content', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:{Cache-Control: no-cache Pragma: no-cache Server: Microsoft-IIS/8.5 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Access-Control-Allow-Headers: Content-Type Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS Date: Thu, 17 Mar 2016 08:32:28 GMT Expires: -1 }}
这是我发布数据的代码
T returnResult = default(T);
HttpClient client = null;
try
{
client = new HttpClient();
client.BaseAddress = new Uri(HostName);
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.Timeout = new TimeSpan(0, 0, 15);
HttpResponseMessage result = null;
StringContent data = null;
if (content != null)
// data = new StringContent(JsonConvert.SerializeObject(content), UTF8Encoding.UTF8, "application/json");
data = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json");
if (method == HttpMethod.Get)
result = await client.GetAsync(endpoint);
if (method == HttpMethod.Put)
result = await client.PutAsync(endpoint, data);
if (method == HttpMethod.Delete)
result = await client.DeleteAsync(endpoint);
if (method == HttpMethod.Post)
result = await client.PostAsync(endpoint, data);
if (result != null)
{
if (result.IsSuccessStatusCode
&& result.StatusCode == System.Net.HttpStatusCode.OK)
{
var json = result.Content.ReadAsStringAsync().Result;
returnResult = JsonConvert.DeserializeObject<T>(json);
}
}
哪里应该是问题?我的API工作正常,启用 CORS
答案 0 :(得分:2)
以下是我在代码中使用PostAsync的示例,我认为“No Content”错误指的是您是不是要向服务器发送任何内容?我希望这个例子有所帮助:
public async Task<bool> PostAppointmet(AppointmentEntity anAppointment)
{
try{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + App.apiToken);
const string resourceUri = ApiBaseAddress + "/citas";
string postBody = JsonConvert.SerializeObject(anAppointment);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.PostAsync (resourceUri, new StringContent (postBody, Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode) {
return true;
}
return false;
}
catch{
return false;
}
}
AppointmentEntity是我的模特:
public class AppointmentEntity
{
public int doctor { get; set; }
public PatientEntity paciente { get; set; }
public DateEntity cita { get; set; }...
}
答案 1 :(得分:1)
尝试像这样使用
var task = client.PostAsync(endpoint,content:data);