Home > Software design >  HttpRequestMessage POST request become GET - Asp.Net Core
HttpRequestMessage POST request become GET - Asp.Net Core

Time:10-25

I am pretty new to Asp.Net Core and I managed to create a mvc project. In This project I have created an API and it is secured with token based authorization. I am trying to consume this api and make a post request to save data to database. To achieve this I have created one API controller and one MVC controller. These two controllers are used with different purposes. In order to consume the api I have to generate a JWT token and attach token to request header. I use MVC controller for that purpose and after attach authorization header, I consume API post endpoint by sending request from MVC controller to API controller. Here is the process.

I have a form to collect product data in view. Data is send to the MVC controller through ajax. Ajax coding part is successfully working and I can see all the data have passed to controller.

MVC Controller

[HttpPost]
public async Task<IActionResult> stockIn([FromBody] Products products)
{
    var user = await _userManager.GetUserAsync(User);
    var token = getToken(user);

    var json = JsonConvert.SerializeObject(products);
    var content = new StringContent(json, Encoding.UTF8, "application/json");

    var httpClient = _clientFactory.CreateClient();

    var request = new HttpRequestMessage(HttpMethod.Post, 
                                         "https://localhost:7015/api/stocks/stockIn/");
    request.Headers.Add("Authorization", "Bearer "   token);
    request.Content = content;
        
    HttpResponseMessage response = await httpClient.SendAsync(request);
    if (response.StatusCode == System.Net.HttpStatusCode.OK)
    {
        var apiData = await response.Content.ReadAsStringAsync();
        return Ok(apiData);
    }

    return StatusCode(StatusCodes.Status500InternalServerError);
}

This code(MVC controller) also works fine, when I debug this just before the request is sent, I can see token and content also have generated and request is attached with them. Request method is also set to POST.enter image description here

Then I put a breakpoint on API controller and once the request is sent, the Request Uri - Api endpoint is hiiting and I can see that request method has become GET and the content become Null

API Controller

[HttpPost]
[Route("StockIn")]
public async Task<IActionResult> StockAdd(HttpRequestMessage httpRequestMessage)
{
    var content = httpRequestMessage.Content;
    string jsonContent = content.ReadAsStringAsync().Result;

    Products products = new Products();
    products = JsonConvert.DeserializeObject<Products>(jsonContent);
    
    await _context.StoresProducts.AddAsync(products);
    await _context.SaveChangesAsync();

    return Ok(new { success = "Stock updated successfully" });
}

When I am hovering over the received httpRequestMessage on API controller :received httpRequestMessage

When I am debuging line by line API controller, A null exception is thrown When request message content access.

Null Exception

I found that there are many posts regarding this issue. I have tried almost every solution mentioned on them.

Tried fixes: None of them work

var httpClient = _clientFactory.CreateClient();
httpClient.DefaultRequestHeaders.ExpectContinue = false;
httpClient.DefaultRequestHeaders.Accept.Add(
     new MediaTypeWithQualityHeaderValue("application/json"));

I also tried changing request Url by adding '/' to end of it, does not work either. Some of the posts has guessed that there must be a redirection but I can not find a redirection also. I think sometime this caused because I am calling the api endpoint via MVC controller action. Since I want to attach token to request header before api calling, I can not find a way to call api endpoint directly without MVC controller action. Please help me to find the issue here or show me how to achieve this task correctly. Thank you.

CodePudding user response:

Most likely, this problem is related to redirect. When you send request with some method and method changes after sending request, it will be about redirect.

Redirect occures in diffrent scenario:

  • Wrong api address
  • Authentication needed

As you said, sometimes url's that does not end with '/' cause to redirect

So send request with postman and check postman log (bottom-left) for better detail.

check if Redirect occoured or not, if redirect occured, so check for reason. also check if WWW_Authenticate exist in headers.

CodePudding user response:

Any particula reason you're expecting the body to bind to the HttpRequestMessage? Have you tried changing the post action to bind to the correct object?

        [HttpPost]
        [Route("StockIn")]
        public async Task<IActionResult> StockAdd(IEnumerable<Products> products)
        {
            await _context.StoresProducts.AddAsync(products);
            await _context.SaveChangesAsync();

            return Ok(new { success = "Stock updated successfully" });

        }
  • Related