SQL Server Creating a controller and I'm getting HTTP error 415 when trying to use HttpPost

r3i60tvu  于 2023-03-17  发布在  其他
关注(0)|答案(2)|浏览(78)

Trying to create a controller in order to add an instance of a class to a SQL database

However, I keep getting a 415 error whenever I try to do. The error specifically shows the following ->

Unhandled exception rendering component: {"type":"https://tools.ietf.org/html/rfc7231#section-6.5.13","title":"Unsupported Media Type","status":415,"traceId":"00-f30954ed2136f9135eeb829d54578d45-69a58efb9fadfcc2-00"}

at blazorTestApp.Client.Repositories.AuthorsRepo.AddAuthor(Authors Author)
   at blazorTestApp.Client.Pages.Authors.AddAuthor.OnSubmit()
   at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
   at Microsoft.AspNetCore.Components.Forms.EditForm.HandleSubmitAsync()
   at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)

The controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using blazorTestApp.Shared.Entities;
using Microsoft.AspNetCore.Mvc;

namespace blazorTestApp.Server.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class AuthorsController : ControllerBase
    {
        private readonly Database DB;
        public AuthorsController(Database DB)
        {
            this.DB = DB;
        }

        [HttpPost]
        public async Task<ActionResult<int>> Post(Authors Author)
        {
            DB.Add(Author);
            await DB.SaveChangesAsync();
            return Ok();
        }
    }
}

The Http service file

namespace blazorTestApp.Client.Classes_FE
{
    public class HttpService : IHttpService
    {
        private readonly HttpClient httpClient;
        public HttpService(HttpClient httpClient)
        {
            this.httpClient = httpClient;
        }

        public async Task<HttpResponse<object>> POST<T>(string url, T data)
        {
            var JsonData = JsonSerializer.Serialize(data);
            var StringContent = new StringContent(JsonData, Encoding.UTF8, "applicaiton/json");
            var ResponseMessage = await httpClient.PostAsync(url, StringContent);
            return new HttpResponse<object>(null, ResponseMessage, ResponseMessage.IsSuccessStatusCode);
        }
    }
}

This file simply inherits from an interface that currently only contains the post method shown. Said interface is the one that is injected into the repository

The repository that sends the Http service

namespace blazorTestApp.Client.Repositories
{
    public class AuthorsRepo
    {
        private IHttpService httpService;
        private string url = "api/Authors";
        public AuthorsRepo(IHttpService httpService)
        {
            this.httpService = httpService;
        }

        public async Task AddAuthor(Authors Author)
        {
            var response = await httpService.POST(url, Author);
            if(!response.Success)
            {
                throw new ApplicationException(await response.GetBodyString());
            }
        }
    }
}

Lastly, the file calling the "AddAuthors" method

@page "/Authors/Add"
@inject AuthorsRepo authorRepo
@inject NavigationManager NavMan

@code
{
    public Authors Author {get; set;} = new Authors();
    public async Task OnSubmit()
    {
        //Unrelated code
        await authorRepo.AddAuthor(Author);
        NavMan.NavigateTo("Authors");
    }
}
iih3973s

iih3973s1#

@Yong Shun is right - we would need to have a look at your client-side / blazor-code to explicitly point out the culprit here.

Generally speaking you should verify the Content-Type attributes value. Most likely you are not sending the Author argument in application/json but e. g. in text/plain .

You can also check in the development-console of your browser. Have a look at you request and verify the Content-Type there. If it is anything other than application/json adapt accordingly on your client-side code.

omvjsjqw

omvjsjqw2#

From POST method in HttpService ,

var StringContent = new StringContent(JsonData, Encoding.UTF8, "applicaiton/json");

It should be "application/json" but not"applicaiton/json".

While you can use HttpClientJsonExtensions.PostAsJsonAsync<TValue>(HttpClient, Uri, TValue, JsonTypeInfo<TValue>, CancellationToken) which will also
Sends a POST request to the specified Uri containing the value serialized as JSON in the request body.

public class HttpService : IHttpService
{
    public async Task<HttpResponse<object>> POST<T>(string url, T data)
    {
        var responseMessage = await httpClient.PostAsJsonAsync(url, data);
        return new HttpResponse<object>(null, ResponseMessage, ResponseMessage.IsSuccessStatusCode);
    }
}

相关问题