Search code examples
.netrestmaui

.Net MAUI 7, Consume API, Get and Get By ID methods are fine but return 405, Method Not Allow for Post, Put and Delete


I have existing api controller for web and MAUI. Consuming from web client is fine, but with MAUI Get and Get by id methods are ok but Post, Put and Delete functions return 405 error.

Web Controller with No Authorization

//[Authorize]
[Route("api/System/GetSsC09EVideoType")]
[HttpGet]
public IHttpActionResult GETSsC09EVideoType()
{
    IList<SsC09EVideoType> entity = SsC09EVideoTypeModel.SaCLSsC09EVideoType();
    return Ok(entity);
}
[Route("api/System/GetSsC09EVideoTypeByID")]
[HttpGet]
public IHttpActionResult GETSsC09EVideoTypeByID(int SID)
{
    SsC09EVideoType entity = SsC09EVideoTypeModel.ReCLSsC09EVideoType(SID);
    return Ok(entity);
}
[Route("api/System/PostSsC09EVideoType")]
[HttpPost]
public IHttpActionResult POSTSsC09EVideoType([FromBody] SsC09EVideoType mySsC09EVideoType)       
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    int count = SsC09EVideoTypeModel.InSsC09EVideoType(mySsC09EVideoType);
    return Ok(count);
}
[Route("api/System/PutSsC09EVideoType")]
[HttpPut]
public IHttpActionResult PUTSsC09EVideoType(int SID, [FromBody] SsC09EVideoType mySsC09EVideoType)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
    bool isUpdate = SsC09EVideoTypeModel.UpSsC09EVideoType(mySsC09EVideoType, SID);
    return Ok(isUpdate);
}
[Route("api/System/DeleteSsC09EVideoType")]
[HttpDelete]
public IHttpActionResult DELETESsC09EVideoType(int SID)
{
    bool isDelete = SsC09EVideoTypeModel.DeSsC09EVideoType(SID);
    return Ok(isDelete);
}

Working code for Get by ID method

public static async Task<SsC09EVideoType> ReCLSsC09EVideoType(string myToken, int SID)
        {
            using (Global.client = new HttpClient())
            {
                Global.client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                Global.client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", myToken);
                Global.client.DefaultRequestHeaders.Add("APIKey", Global.APIKey);
                try
                {
                    SsC09EVideoType myobj = null;
                    HttpResponseMessage response = await Global.client.GetAsync(Global.BaseUrlAddress + "api/System/GetSsC09EVideoTypeByID?SID=" + SID);
                    if (response.IsSuccessStatusCode)
                    {
                        myobj = response.Content.ReadFromJsonAsync<SsC09EVideoType>().Result;
                        return myobj;
                    }
                    
                    return myobj;
                }
            }
          
        }

But for post and others functions return StatusCode: 405, ReasonPhrase: 'Method Not Allowed'

public static async Task<int> InSsC09EVideoType(string myToken, SsC09EVideoType myCl)
        {
            using (Global.client = new HttpClient())
            {
                Global.client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                Global.client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", myToken);
                Global.client.DefaultRequestHeaders.Add("APIKey", Global.APIKey);
                int sid = -1;
                try
                {                    
                    HttpResponseMessage response = await Global.client.PostAsJsonAsync(Global.BaseUrlAddress + "api/System/PostSsC09EVideoType", myCl);
                    if (response.IsSuccessStatusCode)
                    {
                        sid = response.Content.ReadFromJsonAsync<int>().Result;
                        return sid;
                    }                   
                    return sid;
                }               
            }           
        }

Try from MAUI 7 Documentation as follow, also same return 405.

public static async Task<int> InSsC09EVideoType(string myToken, SsC09EVideoType myCl)
     {
           using (Global.client = new HttpClient())
           {
                Global.client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                Global.client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", myToken);
                Global.client.DefaultRequestHeaders.Add("APIKey", Global.APIKey);

                Uri uri = new Uri(string.Format(Global.BaseUrlAddress + "api/System/PostSsC09EVideoType", string.Empty));
                JsonSerializerOptions _serializerOptions = new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                    WriteIndented = true
                };
                int sid = -1;
                try
                {
                    string json = System.Text.Json.JsonSerializer.Serialize<SsC09EVideoType>(myCl, _serializerOptions);
                    StringContent content = new StringContent(json, Encoding.UTF8, "application/json");                    
                    HttpResponseMessage response = await Global.client.PostAsync(uri,content);
                    return sid;
                }              
            }           
        }

Testing with another HttpRequestMessage also 405 return


Uri uri = new Uri(string.Format(Global.BaseUrlAddress + "api/System/PostSsC09EVideoType", string.Empty)); 
HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, uri);
message.Headers.Add("Accept", "application/json");
message.Headers.Add("APIKey", "123");
message.Content = JsonContent.Create<SsC09EVideoType>(myCl);

HttpResponseMessage response = await Global.client.SendAsync(message);

I’m testing with local device(Android 10.0-api 29). Having problem with API Key Header.


Solution

  • Solved! Because of url format. My original format https://www.example.com/api cause 405 method not allow for post,put and delete. By changing into https://example.com/api solve everything.