要在C# webserver中處理跨域請求,需要在服務器端配置允許跨域請求的設置。以下是一種常見的處理跨域請求的方法:
// 添加跨域請求處理
if (context.Request.HttpMethod == "OPTIONS")
{
context.Response.AddHeader("Access-Control-Allow-Origin", "http://example.com");
context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
context.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
context.Response.AddHeader("Access-Control-Max-Age", "1728000");
context.Response.End();
}
// 允許所有域的跨域請求
context.Response.AddHeader("Access-Control-Allow-Origin", "*");
context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
context.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
context.Response.AddHeader("Access-Control-Max-Age", "1728000");
<system.webServer>
<handlers>
<add name="OPTIONSVerbHandler" path="*" verb="OPTIONS" modules="ProtocolSupportModule" resourceType="Unspecified" requireAccess="Script" />
</handlers>
</system.webServer>
通過以上配置,C# webserver應該能夠正確處理跨域請求。請注意,跨域請求可能會導致安全風險,因此建議在僅在必要時開啟跨域請求。