HttpClient {StatusCode: 415, ReasonPhrase: '不支持的媒体类型'

Xni*_*tor 2 c# asp.net asp.net-web-api

我尝试在方法中调用我的 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);
            }
        }
Run Code Online (Sandbox Code Playgroud)

还有我的 API 方法:

    [HttpGet]
    [Route ("api/getsuggestions/")]
    public async Task<IHttpActionResult> GetSuggestions(BookingTableEntity bookingTable)
    {
        //code
    }
Run Code Online (Sandbox Code Playgroud)

我一直在使用相同的代码来调用我的其他方法,除了这种情况外,它一直工作正常。我不明白它们之间的区别。

这是一个示例,我使用基本相同的代码并且可以正常工作。

[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");
    }
Run Code Online (Sandbox Code Playgroud)

和 API:

[HttpGet]
    [Route("api/getbookingsystemsfromcity/{city}")]
    public async Task<IHttpActionResult> GetBookingSystemsFromCity(string city)
    {
        //code
    }
Run Code Online (Sandbox Code Playgroud)

Ale*_*der 8

Web API 期望客户端指定Content-Type标头,但您不能HttpClient在发出GET请求时指定此标头,因为它没有正文。即使您application/json在中指定,StringContent您也将对象错误地传递到请求中。考虑使用POST来解决您的问题。这是POST用于传输复杂对象的常见做法。

更新 api 以接受 POST

[HttpPost]
[Route ("api/getsuggestions/")]
public async Task<IHttpActionResult> GetSuggestions(BookingTableEntity bookingTable)
Run Code Online (Sandbox Code Playgroud)

更新请求代码

var content = new StringContent(JsonConvert.SerializeObject(city), Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, content);
string result = await response.Content.ReadAsStringAsync();
Run Code Online (Sandbox Code Playgroud)

笔记

不要处理HttpClient每个请求,它旨在被重用