Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

224
Vistas
how to restrict cross origin request for other domains using CORs

I am working on asp.net web api project I want allow only my domain access but its working fine when i calling my webapi from JavaScript but problem is when i calling web api from c# code it allows any domine to access how can i restrict this i want give access only for my domain

I am working on asp.net web api project I want allow only my domain access but its working fine when i calling my webapi from JavaScript but problem is when i calling web api from c# code it allows all domine to access how can i restrict this..? i want give access only for my domain

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can use Microsoft.AspNet.WebApi.Cors, a Nuget package from Microsoft. Follow these step:

  1. install package for your API project.

  2. add one line code to your App_Start/WebApiConfig.cs file to enable the function: config.EnableCors();

    using System.Web.Http;
    namespace WebService
    {
        public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                // New code
                config.EnableCors();
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }
    }
    
  3. use attribute in your controller or action like this:

    using System.Net.Http;
    using System.Web.Http;
    using System.Web.Http.Cors;
    namespace WebService.Controllers
    {
        [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
        public class TestController : ApiController
        {
            // Controller methods not shown...
        }
    }
    

You can get more info here

about 4 years ago · Juan Pablo Isaza Denunciar

0

1=> var cors = new EnableCorsAttribute("http://mydomain", "*", "*"); config.EnableCors(cors); I wrote this code in web config file as global level but its working fine when I am calling my web api from client side its allowing only for specified domain

2=> This is my Client side code

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.2.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$ $.ajax({
                url: "http://localhost:49676/Account/ValidLogin",
                method: "get",
                data: Employee,
                dataType: "json",
                //contentType: "application/json",
                success: function (data) {
                    GetAllEmployee(data);

                    alert("success");
                    console.log(data);
                },
                error: function (err) {
                    alert("error");
                }
3. I wrote some code I web config file to restrict other domain request but when i calling web api by client side it allowing any domine to access so my problem is I want to restrict my api form Other public domain

Here is my server side code

protected void btnDelete_Click(object sender, EventArgs e) {

        string strUrl = string.Format("http://mydomain/account/validlogin?username=admin&password=admin");
        HttpWebRequest requestObjectGet = (HttpWebRequest)HttpWebRequest.Create(strUrl);
        requestObjectGet.Method = "GET";
        HttpWebResponse responseObjectGet = null;
        responseObjectGet = (HttpWebResponse)requestObjectGet.GetResponse();

        string strresulttest = null;

        using (Stream stream = responseObjectGet.GetResponseStream())
        {
            StreamReader sr = new StreamReader(stream);
            strresulttest = sr.ReadToEnd();
            JavaScriptSerializer js = new JavaScriptSerializer();
            string StrToken = js.Deserialize<string>(strresulttest);
            Session["ApiToken"] = StrToken;

}

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda