(精华)2020年8月17日 WebApi解决跨域问题
发布日期:2021-06-29 15:10:02 浏览次数:3 分类:技术文章

本文共 1063 字,大约阅读时间需要 3 分钟。

  1. negut引用:MIcrosoft.AspNet.WebApi.Cors
  2. 添加配置如下:webapi网站就可以解决跨域问题

全局配置

public static class WebApiConfig{
public static void Register(HttpConfiguration config) {
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));//全部都允许, }}

方法配置

[EnableCors(origins: "http://localhost:9099/", headers: "*", methods: "GET,POST,PUT,DELETE")]public Users GetUserByID(){
}

行为特性配置跨域

public class CustomActionFilterAttribute : ActionFilterAttribute{
public override void OnActionExecuting(HttpActionContext actionContext) {
} public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) {
actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*"); }}

注意点

jq跨域兼容处理

//microsoft.aspnet.webapi.corsjQuery.support.cors = true;var location = "http://localhost:8088";$("#btnGetCors1").on("click", function () {
$.ajax({
url: location + "/api/users/GetUserByID", type: "get", data: {
"id": 1 }, success: function (data) {
alert(data); }, datatype: "json" });});

转载地址:https://codeboy.blog.csdn.net/article/details/108054754 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:(精华)2020年8月17日 C#基础知识点 Log4日志的用法
下一篇:(精华)2020年8月17日 WebApi行为过滤处理方式

发表评论

最新留言

很好
[***.229.124.182]2024年04月27日 07时13分23秒