locked
Core web api runtime ToHttpResponseMessage error RRS feed

  • Question

  • User-257070954 posted

    Hi All ,

              I am getting below error when  writing .net core web API 

    $exception {"Could not load file or assembly 'System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The system cannot find the file specified.":"System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"} System.IO.FileNotFoundException

    Below is my code

    [Route("api/[controller]")]
    [ApiController]


    public class ModuleController : ControllerBase
    {
    [HttpGet]
    public HttpResponseMessage Get()
    {
    try
    {
    string connecton = "server=dev-server;database=Prime; persist security info = True; Integrated Security = SSPI";
    string strResult = "";
    SqlConnection connection = new SqlConnection(connecton);
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = connection;
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "Prime.GetModule";
    connection.Open();
    SqlDataReader reader = cmd.ExecuteReader();

    if (reader.HasRows)
    {
    reader.Read();
    //string JSON strResult = JsonConvert.de(reader[0]);
    //TaskModel tmdel = JsonConvert.DeserializeObject<TaskModel>(reader[0]);

    strResult = reader[0].ToString();

    }

    connection.Close();

    var apiResponse = new ModuleGetResponse();
    apiResponse.lstModuleDetails = JsonConvert.DeserializeObject<List<ModuleModel>>(strResult);
    apiResponse.AppendSuccessMessage("", "All modules listed successfully.");
    return apiResponse.ToHttpResponseMessage(HttpStatusCode.OK);    Getting error from here runtime

    }
    catch (Exception ex)
    {
    // return new List<ModuleModel> { { } }
    return new BaseErrorResponse()
    .AppendErrorMessage("", "Request cannot be processed due to unknown error.")
    .ToHttpResponseMessage(HttpStatusCode.ServiceUnavailable);
    }
    }
    }

    Friday, September 6, 2019 7:30 AM

Answers

  • User711641945 posted

    Hi binustrat,

    var response = new HttpResponseMessage()
    {
    // Content = new StringContent(Json.Encode(this)),
    // StatusCode = statusCode
    };
    response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

    As my previous post,you need to serialize object to json.In asp.net core,it does not support Json.Encode().So you need to change like below:

    Content = new StringContent(JsonConvert.SerializeObject(this)),

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, September 13, 2019 9:30 AM

All replies

  • User711641945 posted

    Hi binustrat,

    return apiResponse.ToHttpResponseMessage(HttpStatusCode.OK);    Getting error from here runtime

    You need to share the ToHttpResponseMessage method that could reproduce your issue.

    $exception {"Could not load file or assembly 'System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The system cannot find the file specified.":"System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"} System.IO.FileNotFoundException

    Actually,this file does not contain in ASP.Net Core. It is for .net framework.Do you want to serialize and deserialize object?If so,I suggest that you can use Newtonsoft.Json.

    Best Regards,

    Rena

    Friday, September 6, 2019 9:11 AM
  • User-257070954 posted

    Below providing my function code

            

    public HttpResponseMessage ToHttpResponseMessage(HttpStatusCode statusCode)
    {
    var response = new HttpResponseMessage()
    {
    // Content = new StringContent(Json.Encode(this)),
    // StatusCode = statusCode
    };
    response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

    if (this._errorState)
    {
    this.ResultCode = "ERR";
    response.StatusCode = HttpStatusCode.BadRequest;
    throw new HttpResponseException(response);
    }
    return response;
    }

    Friday, September 6, 2019 11:13 AM
  • User475983607 posted

    In Web API simply return the type. 

    // GET: api/Todo
    [HttpGet]
    public async Task<ActionResult<IEnumerable<TodoItem>>> GetTodoItems()
    {
        return await _context.TodoItems.ToListAsync();
    }
    
    // GET: api/Todo/5
    [HttpGet("{id}")]
    public async Task<ActionResult<TodoItem>> GetTodoItem(long id)
    {
        var todoItem = await _context.TodoItems.FindAsync(id);
    
        if (todoItem == null)
        {
            return NotFound();
        }
    
        return todoItem;
    }

    It's not clear why yo went down your current path but I recommend following programming patterns found in the standard Web API documentation.

    https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-2.2&tabs=visual-studio

    Friday, September 6, 2019 12:24 PM
  • User711641945 posted

    Hi binustrat,

    >>Could not load file or assembly 'System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

    I could not reproduce your issue due to the code you shared does not related to this package.I suggest that you need to set breakpoint related to your ToHttpResponseMessage action.And test step by step to find the line which makes error.I have said in previous post,this package is for .net framework.Please check the target framework in your project.If you want to use the package,it should be .net framework.

    Best Regards,

    Rena

    Monday, September 9, 2019 10:03 AM
  • User-257070954 posted

    Hi Rena,

                      I am  getting this error from 

                       response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); line

                        My target framework is .NET Core 2.2. The code i am mentioned above  used in non core application with out any issue and i trying to use same code in .Net core

    Thursday, September 12, 2019 5:22 AM
  • User475983607 posted

    The error in your first thread...

    $exception {"Could not load file or assembly 'System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The system cannot find the file specified.":"System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"} System.IO.FileNotFoundException

    ...is usually related to the AJAX toolkit which is not comparable with ASP Core 2.2.  The AJAX Tools kit is used in ASP.NET Web Forms.

    Thursday, September 12, 2019 10:06 AM
  • User711641945 posted

    Hi binustrat,

    var response = new HttpResponseMessage()
    {
    // Content = new StringContent(Json.Encode(this)),
    // StatusCode = statusCode
    };
    response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

    As my previous post,you need to serialize object to json.In asp.net core,it does not support Json.Encode().So you need to change like below:

    Content = new StringContent(JsonConvert.SerializeObject(this)),

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, September 13, 2019 9:30 AM
  • User-257070954 posted

    Hi Rena,

                The above code you mentioned help me to avoid an error. But it is not listing data. Below giving my code and output I am receiving

                  ResourceBl resourceBl = new ResourceBl();
                   var apiResponse = new ResourceGetResponse();
                   apiResponse.lstResDetails = JsonConvert.DeserializeObject<List<ResourceModel>>(resourceBl.GetResource()); // apiResponse.lstResDetails is model list
                  apiResponse.AppendSuccessMessage("", "All resources listed successfully.");
                  return apiResponse.ToHttpResponseMessage(HttpStatusCode.OK);

    Below giving ToHttpResponseMessage method code

    public HttpResponseMessage ToHttpResponseMessage(HttpStatusCode statusCode)
    {
    var response = new HttpResponseMessage()
    {
    Content = new StringContent(JsonConvert.SerializeObject(this)),
    StatusCode = statusCode
    };
    response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

    if (this._errorState)
    {
    this.ResultCode = "ERR";
    response.StatusCode = HttpStatusCode.BadRequest;

    }
    return response;
    }

                

    Monday, September 16, 2019 5:11 AM
  • User711641945 posted

    Hi binustrat,

    The above code you mentioned help me to avoid an error.

    This thread have solved yet.You need to mark the helpful answer to close the thread and post a new thread with detailed code to ask how to get the listing data.

    Best Regards,

    Rena

    Tuesday, September 17, 2019 6:46 AM