没有& # 39;Access-Control-Allow-Origin& # 39;当ajax请求在webapi上对实
本文关键字:webapi Access-Control-Allow-Origin 没有 ajax 请求 | 更新日期: 2023-09-27 18:04:43
我有关于使用WebApi的问题,让我告诉你我在小场景中的情况;我有一个Visual Studio 2015解决方案,由2个项目组成。其中一个是WebApi项目,另一个是MVC web应用程序。在WebApi方面,我有2类通过外键引用完整性。当我从web应用程序发出ajax请求时,我没有得到"Access-Control-Allow-Origin"错误。但是,当我取消导航属性(我的意思是删除参照完整性),并在WebApi控制器手动填充类内的对象列表,它的工作没有错误。也许我错过了什么,但我真的找不到。有人能帮帮我吗?提前感谢。
这是我的类;
public class BaseEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
private DateTime _EklenenTarih = DateTime.Now;
[Required]
public DateTime EklenenTarih { get { return _EklenenTarih; } set { _EklenenTarih = value; } }
private DateTime _GuncellenenTarih = DateTime.Now;
[Required]
public DateTime GuncellenenTarih { get { return _GuncellenenTarih; } set { _GuncellenenTarih = value; } }
}
public class CariTanim : BaseEntity
{
[Required]
public string Ad { get; set; }
[Required]
public string SoyAd { get; set; }
[Required]
public string Email { get; set; }
public virtual ICollection<CariHaraket> Haraketler { get; set; }
}
public class CariHaraket: BaseEntity
{
[Required]
public int CariId { get; set; }
[Required]
public decimal Tutar { get; set; }
[Required]
public DateTime Tarih { get; set; }
[ForeignKey("CariId")]
public virtual CariTanim cari { get; set; }
}
这是我的控制器;
public class CariController : ApiController
{
private CariContex db = new CariContex();
[System.Web.Mvc.HttpGet]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public object GetAllCari()
{
List<CariTanim> carilist = db.cariler.ToList();
return carilist;
}
}
我的上下文也在这里;
public class CariContex: DbContext
{
public CariContex()
{
Configuration.ProxyCreationEnabled = true;
Configuration.LazyLoadingEnabled = true;
Database.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["ConnSTR"].ConnectionString;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
base.OnModelCreating(modelBuilder);
}
public DbSet<CariTanim> cariler { get; set; }
public DbSet<CariHaraket> hareketKayitlari { get; set; }
}
我的webapiconfig也在这里;
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.EnableCors();
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
,最后我发出这样的ajax请求;
$.ajax({
url: _url + "Cari/GetAllCari",
type: "GET",
contentType: "application/json",
dataType: "JSON",
cache: false,
success: function (CariList) {
if (CariList.length > 0)
{
if (CariList[0].ResponseCode == 1) {
$("#CariList").empty();
$.each(CariList, function (index, cari) {
console.log(cari);
$("#CariList").append("<li>" + cari.Ad + " - " + cari.SoyAd + "</li>");
});
}
else {
alert(CariList[0].ResponseMessage);
}
}
},
error: function (request) {
console.log(request);
var msg = JSON.parse(request.responseText);
alert("Failed:'n'n" + request.status + " - " + request.statusText + "'n'n" + msg["Message"]);
}
})
您错过了告诉jQuery它正在发出CORS请求的步骤。将ajax请求更改为:
$.ajax({
url: _url + "Cari/GetAllCari",
type: "GET",
contentType: "application/json",
dataType: "JSON",
cache: false,
xhrFields: {withCredentials: true},
success: function (CariList) {
if (CariList.length > 0)
{
if (CariList[0].ResponseCode == 1) {
$("#CariList").empty();
$.each(CariList, function (index, cari) {
console.log(cari);
$("#CariList").append("<li>" + cari.Ad + " - " + cari.SoyAd + "</li>");
});
}
else {
alert(CariList[0].ResponseMessage);
}
}
},
error: function (request) {
console.log(request);
var msg = JSON.parse(request.responseText);
alert("Failed:'n'n" + request.status + " - " + request.statusText + "'n'n" + msg["Message"]);
}
})
你应该可以走了
my webapi web。
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301879
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="ConnSTR" connectionString="data source=(localdb)'MSSQLLocalDB;integrated security=SSPI;
 attachdbfilename=|DataDirectory|Cari.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings></appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
</system.web>
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE='"Web'" /optionInfer+" />
</compilers>
</system.codedom>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
和我的web应用程序web。
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<appSettings>
<add key="webpages:Version" value="3.0.0.0"/>
<add key="webpages:Enabled" value="false"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.2"/>
<httpRuntime targetFramework="4.5.2"/>
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
</httpModules>
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs"
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE='"Web'" /optionInfer+"/>
</compilers>
</system.codedom>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<remove name="ApplicationInsightsWebTracking"/>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"
preCondition="managedHandler"/>
</modules>
</system.webServer>
</configuration>