要在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应该能够正确处理跨域请求。请注意,跨域请求可能会导致安全风险,因此建议在仅在必要时开启跨域请求。