System.Net.WebException: The remote server returned an error: (400) Bad Request dotnet and core

  Uncategorised
  1. MVC code:

    [HttpPost]
    public JsonResult SearchUser(SearchContactTracingDataRequest request)
    {
        try
        {
            object input = new
            {
                UserId = request.UserId,
                FromDate = request.FromDate.ToString("yyyy-mm-dd hh:mm"),
                ToDate = request.ToDate.ToString("yyyy-mm-dd hh:mm"),
                Radius = request.Radius
            };
            string inputJson = (new JavaScriptSerializer()).Serialize(input);
            var client = new WebClient();
            client.Headers.Add("ContentType:application/json");
            client.Headers.Add("Accept:application/json");
            if (Session["Token"] != null)
            {
                client.Headers.Add("Authorization", "Bearer " + Session["Token"]);
            }
            client.Encoding = Encoding.UTF8;
            string res = client.UploadString(apiUrl + "/Account/SearchContactTracingData",inputJson);
            Response<List<SearchContactTracingDataResponse>> objResponse = JsonConvert.DeserializeObject<Response<List<SearchContactTracingDataResponse>>>(res);                 
            return Json(res, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    
  2. WebApi(dot net core):

    public async Task<Response<List>>SearchContactTracingData(SearchContactTracingDataRequest request)
    {
    try
    {
    List dataResponses = new List();
    var nearByUsers = await _contactTracingDbContext.usp_GetNearByUsers.FromSql($"usp_GetNearByUsers {request.UserId},{request.FromDate},{request.ToDate},{request.Radius}").ToListAsync();
    //Using bluetooth data
    foreach (var item in nearByUsers)
    {
    SearchContactTracingDataResponse dataResponse = new SearchContactTracingDataResponse();
    dataResponse.BluetoothId = item.BluetoothId;
    dataResponse.DeviceId = item.DeviceId;
    dataResponse.Email = item.Email;
    dataResponse.FirstName = item.FirstName;
    dataResponse.LastName = item.LastName;
    dataResponse.Mobile = item.Mobile;
    dataResponses.Add(dataResponse);
    }
    return new Response<List>
    {
    Result = dataResponses,
    Status = StatusCode.Success,
    StatusMessage = "Success"
    };
    }
    catch (Exception ex)
    {
    return new Response<List>
    {
    Result = null,
    Status = StatusCode.Error,
    StatusMessage = "Error",
    Error = ex.Message,
    };
    }
    }

Source: Visual Studio Questions

LEAVE A COMMENT