Consuming C# Web Api with Reactjs

Asked

Viewed 462 times

0

I am trying to consume a Webapi created in C# webApi2 in an application created in reactJs, when I request the Api using the browser or Postman I have the information returned, but when I try to do it by the React application returns the message below:

Erro ao buscar dados pelo front

I initially thought it was a Webapi configuration problem, so I set up CORS to allow any request, but it still didn’t work. Below my both web service and request settings.

Call with the fetch

    static sendEmployeeEdit(data){
        return dispatch => {
            fetch(`http://192.168.171.13:8096/Employees/Update/123`,{
                method:'POST',
                headers:{ 
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: data
            })
            .then(response =>{
                if(response.ok){
                    return response.json();
                }else
                    return {classe: "error"};
            })
            .then(items =>{
                console.log(items);
                //dispatch(editedEmployee(items.classe));
                //return items.classe;
            })
        }
    }

Cors configuration:

using System.Web.Http;
using System.Web.Http.Cors;

namespace Intranet_Service.Controllers
{
   [EnableCors(origins: "*", headers: "*", methods: "*")] // tune to your needs
   [RoutePrefix("Employees")]
   public class EmployeeController : ApiController
   {
      [Route("Update/{Token}")]
      [HttpPost]
      public async System.Threading.Tasks.Task<IHttpActionResult> UpdateEmployeesAsync(string Token)
       {
         var ReturnData = await Request.Content.ReadAsStringAsync();
         return Json(new { DataObject = Token + " " + ReturnData });
       }

      [Route("Teste/{Token}")]
      [HttpGet]
      public async System.Threading.Tasks.Task<IHttpActionResult> Teste(string Token)
      {
         var ReturnData = await Request.Content.ReadAsStringAsync();
         return Json(new { DataObject = Token + " " + ReturnData });
      }
   }
}

Webapiconfig

using System.Web.Http;

namespace Intranet_Service
{
  public static class WebApiConfig
  {
    public static void Register(HttpConfiguration config)
    {
        config.EnableCors();
        config.MapHttpAttributeRoutes();
    }
  }
}

Global.asax.Cs

using System.Web.Http;

namespace Intranet_Service
{
  public class WebApiApplication : System.Web.HttpApplication
  {
     protected void Application_Start()
     {
        GlobalConfiguration.Configure(WebApiConfig.Register);
     }
  }
}
  • You’re not wearing OWIN?

  • No, to tell you the truth I didn’t even know what it was until just researching.

  • Try to remove the attribute EnableCors and try again

  • Returned me the same mistake

  • Access to fetch at 'http://192.168.171.13:8096/Employees/Update/123' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested source Rerequested. If an Opaque Response serves your needs, set the request’s mode to 'no-Cors' to fetch the Resource with CORS disabled.

  • Are these all CORS settings? There is no class Startup in the project?

  • I was able to send the data, my JSON was sending the values of the fields separating by type, that is, string as string and integer as integer, after I put quotes in the fields that were numerical worked. Another thing is that using fecthApi didn’t work, but using $.Ajax passing dataType: "json" worked.

Show 2 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.