【发布时间】:2019-08-23 17:23:02
【问题描述】:
我尝试在一个方法中调用我的 API,但出现错误:{StatusCode: 415, ReasonPhrase: 'Unsupported Media Type'。我一直在环顾四周,发现很多人都有同样的问题,但通过在创建 StringContent 时添加媒体类型已解决。我已经设置了字符串内容,但我仍然得到错误。
这是我尝试调用 API 的方法:
[HttpGet]
public async Task<ActionResult> TimeBooked(DateTime date, int startTime, int endTime, int id)
{
var bookingTable = new BookingTableEntity
{
BookingSystemId = id,
Date = date,
StartTime = startTime,
EndTime = endTime
};
await Task.Run(() => AddBooking(bookingTable));
var url = "http://localhost:60295/api/getsuggestions/";
using (var client = new HttpClient())
{
var content = new StringContent(JsonConvert.SerializeObject(bookingTable), Encoding.UTF8, "application/json");
var response = await client.GetAsync(string.Format(url, content));
string result = await response.Content.ReadAsStringAsync();
var timeBookedModel = JsonConvert.DeserializeObject<TimeBookedModel>(result);
if (response.IsSuccessStatusCode)
{
return View(timeBookedModel);
}
}
还有我的 API 方法:
[HttpGet]
[Route ("api/getsuggestions/")]
public async Task<IHttpActionResult> GetSuggestions(BookingTableEntity bookingTable)
{
//code
}
我一直在使用相同的代码来调用我的其他方法,除了这种情况外,它一直运行良好。我不明白它们之间的区别。
这是一个示例,我使用基本相同的代码并且它可以工作。
[HttpGet]
public async Task<ActionResult> ChoosenCity(string city)
{
try
{
if (ModelState.IsValid)
{
var url = "http://localhost:60295/api/getbookingsystemsfromcity/" + city;
using (var client = new HttpClient())
{
var content = new StringContent(JsonConvert.SerializeObject(city), Encoding.UTF8, "application/json");
var response = await client.GetAsync(string.Format(url, content));
string result = await response.Content.ReadAsStringAsync();
var bookingSystems = JsonConvert.DeserializeObject<List<BookingSystemEntity>>(result);
var sortedList = await SortListByServiceType(bookingSystems);
if (response.IsSuccessStatusCode)
{
return View(sortedList);
}
}
}
}
catch (Exception ex)
{
throw ex;
}
return RedirectToAction("AllServices");
}
还有 API:
[HttpGet]
[Route("api/getbookingsystemsfromcity/{city}")]
public async Task<IHttpActionResult> GetBookingSystemsFromCity(string city)
{
//code
}
【问题讨论】:
-
GET 请求不能有正文,因此它们也不能有内容类型。看起来服务器一看到无效的标头就拒绝了请求,甚至没有尝试查看是否有正文。
标签: c# asp.net asp.net-web-api