我正在使用Web-API 2创建Web服务。我使用以下代码启用了跨源资源共享。
的Web.config
<?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=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<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" />
<httpRuntime targetFramework="4.5" />
</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.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.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="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<connectionStrings>
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
<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" />
<customErrors mode="Off"/>
</handlers>
<httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Methods" value="*" /> </customHeaders> </httpProtocol>
</system.webServer></configuration>
APIController:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using ProActiveWebServices.Models;
using System.Web.Hosting;
using System.IO;
using System.Drawing.Imaging;
using System.Net.Http.Headers;
using System.Drawing;
using System.Net.Mail;
using System.Text;
namespace ProActiveWebServices.Controllers
{
public class EnquiryController : ApiController
{
ProActiveEntities db = new ProActiveEntities();
List<Enquiry> en = new List<Enquiry> { };
List<City> ct = new List<City> { };
EnquiryList enquiryList = new EnquiryList();
CityList cityList = new CityList();
// GET api/<controller>
[Route("api/GetAllEnquiry")]
public HttpResponseMessage Get()
{
try
{
if (CheckAuthentication(Request) || 1==1)
{
var enquiry = db.tbl_Enquiry.ToList();
foreach (var e in enquiry)
{
Enquiry _enquiry = new Enquiry();
_enquiry.FullName = e.FullName;
_enquiry.Id = e.EnquiryID;
_enquiry.CompanyName = e.CompanyName;
_enquiry.ContactAddress = e.ContactAddress;
_enquiry.Email = e.Email;
_enquiry.fk_CityID = e.fk_CityID;
_enquiry.Comment = e.Comment;
en.Add(_enquiry);
}
enquiryList.EnquiryLists = en;
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, new { Enquiry = enquiryList });
return response;
}
else
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, new { Error = "Invalid Header and Authorization" });
return response;
}
}
catch (Exception ex)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, "Error:" + ex.ToString());
return response;
}
}
}
}
这是我的WebAPIConfig.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Cors;
namespace ProActiveWebServices
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var cors = new EnableCorsAttribute("*", "*", "*");
// Web API routes
config.MapHttpAttributeRoutes();
config.EnableCors(cors);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
}
}
现在,当我在localhost上运行它时,它工作正常。但是当在godaddy上托管web服务时,我收到500内部服务器错误。 我也在web.config中启用了Access-Control-Allow-Origin。但仍然没有成功
答案 0 :(得分:0)
这是我在GoDaddy上获得服务所必需的。
将以下内容添加到您的web.config中(将此行添加到您的web.config有一些缺点,进行一些研究,因为我无法回忆,但是如果你谷歌的话,那就是关于它的信息):
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
您可能还需要添加
<system.web>
<securityPolicy>
<trustLevel name="Full" policyFile="internal" />
</securityPolicy>
<trust level="Full" originUrl="" processRequestInApplicationTrust="true" />
</system.web>
答案 1 :(得分:0)
如果您使用web api并在Web配置中通过EnableCors启用Cors,我刚刚遇到此错误,那么您不需要在Web配置中再次编写它。
如果您的代码中没有任何未处理的异常,那么在您的web api配置中编写此代码
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
var cors = new EnableCorsAttribute(
origins: "*",
headers: "*",
methods: "*");
config.EnableCors(cors);
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}